【问题标题】:Looping over column names and adding column names to dplyr summary tables in R遍历列名并将列名添加到 R 中的 dplyr 汇总表
【发布时间】:2022-11-15 11:01:15
【问题描述】:

我想遍历许多列以获得每个列的每个因子级别的 dplyr 年龄摘要。我还想将列名添加到我创建的 dplyr 表中,但我在分配它时也遇到了问题

我尝试使用 assign 执行以下操作:

for(var in c("Sex", "Smoke", "Diabetes", "HIV")) {
  assign(paste0("mean_",var))<-df%>%group_by(var) %>%
    summarise(meanAge=mean(Age), sdAge=sd(Age))
}

我基本上想要每一列的年龄汇总表(mean_Sex、mean_Smoke、mean_Diabetes 和 mean_HIV)

但我收到错误:

group_by_prepare() 中的错误: !必须按.data 中的变量分组。

  • 未找到列 var。 运行rlang::last_error()查看错误发生的位置。

任何人都可以帮助解决这个问题吗?

数据示例:

structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
    Sex = structure(c(2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 
    2L, 1L), .Label = c("F", "M"), class = "factor"), Smoke = structure(c(3L, 
    1L, 1L, 3L, 2L, 2L, 2L, 3L, 3L, 1L, 1L, 3L), .Label = c("N", 
    "NA", "Y"), class = "factor"), Diabetes = structure(c(3L, 
    1L, 3L, 3L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 2L), .Label = c("N", 
    "NA", "Y"), class = "factor"), HIV = structure(c(1L, 1L, 
    2L, 3L, 3L, 3L, 3L, 2L, 1L, 1L, 2L, 1L), .Label = c("N", 
    "NA", "Y"), class = "factor"), Age = c(23, 24, 43, 35, 18, 
    29, 25, 17, 22, 20, 55, 54)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

    标签: r for-loop dplyr


    【解决方案1】:

    为避免显式 for 循环,您可以尝试:

    grp_cols <- c("Sex", "Smoke", "Diabetes", "HIV")
    dt %>% 
        group_by(across(all_of(grp_cols))) %>% 
        summarise(meanAge=mean(Age), sdAge=sd(Age))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2018-11-05
      • 2021-03-09
      • 2018-11-07
      相关资源
      最近更新 更多