重命名并组合R中的行

时间:2018-05-22 13:42:40

标签: r shiny tidyr

我正在尝试将几行合并到一个数据帧中。以下是我用来获取输出数据帧的代码。

myData <- reactive({
age_selected <- input$selected_age
gender_selected <- input$selected_gender
ethnicity_selected <- input$selected_ethnicity


df <- with_demo_vars %>%
  filter(age == age_selected) %>%
  filter(gender == gender_selected) %>%
  filter(ethnicity == ethnicity_selected) %>%
  pct_ever_user(type = "SM")

 #df[, c("variable",  "sum_wts", "se")]
 #interval=paste(df$ci_l,df$ci_u,collapse = "-")
 df <- mutate(df, intervals= paste("(",round(ci_l,digits = 3), round(ci_u,digits = 3),sep = "-",")"))
#   %>% c("variable", paste("mean",x), "sum_wts", "se")
 #df[c(("variable", "mean", "sum_wts", "se","x")]

})

我得到的输出是:enter image description here

我想要的输出是格式化的,只有几个字段:

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以先使用粘贴功能创建一个新列,以合并两列intervalsdf$Mean1<-paste(df$mean,df$intervals,sep=" ") new_df<-select(df, variable, Mean1, se, n, sum_wts) colnames(new_df)[1]<-"variable" colnames(new_df)[2]<-"Mean" colnames(new_df)[3]<-"Standard" colnames(new_df)[4]<-"N" colnames(new_df)[5]<-"Wighted N" 。然后按所需顺序选择列。然后重命名每列。

peekAll

答案 1 :(得分:1)

您可以在Mean内创建Standardmutate,然后在重命名nsum_wts时选择所需的列:

library(dplyr)

df <- mutate(df, intervals= paste("(",round(ci_l,digits = 3), 
                                  round(ci_u,digits = 3),
                                  sep = "-",")"),
             Mean = paste(mean, intervals),
             Standard = paste0(se*100, "%")) %>%
  select(variable, Mean, Standard, N = n, `Weighted N` = sum_wts)