【问题标题】:dplyr group_by loop through different columnsdplyr group_by 循环遍历不同的列
【发布时间】:2019-03-13 23:05:16
【问题描述】:

我有以下数据;

我想使用 group_by 创建三个不同的数据框并总结 dplyr 函数。这些将是 df_Sex、df_AgeGroup 和 df_Type。对于这些列中的每一列,我想执行以下功能;

 df_Sex =  df%>%group_by(Sex)%>%summarise(Total = sum(Number))

有没有办法使用 apply 或 lapply 将这三列(Sex、AgeGrouping 和 Type)中每一列的名称传递给这些创建 3 个数据框?

【问题讨论】:

    标签: r dplyr apply lapply


    【解决方案1】:

    这会起作用,但会创建一个数据框列表作为您的输出

    ### Create your data first    
    
    df <- data.frame(ID = rep(10250,6), Sex = c(rep("Female", 3), rep("Male",3)), 
                         Population = c(rep(3499, 3), rep(1163,3)), AgeGrouping =c(rep("0-14", 3), rep("15-25",3)) , 
                         Type = c("Type1", "Type1","Type2", "Type1","Type1","Type2"), Number = c(260,100,0,122,56,0))
    
    gr <- list("Sex", "AgeGrouping","Type")
    
    df_list <- lapply(gr, function(i) group_by(df, .dots=i) %>%summarise(Total = sum(Number)))
    

    【讨论】:

      【解决方案2】:

      这是一种方法:

      f <- function(x) {
           df %>% 
               group_by(!!x) %>% 
               summarize(Total = sum(Number))
      }
      
      lapply(c(quo(Sex), quo(AgeGrouping), quo(Type)), f)
      

      可能有更好的方法来做到这一点,我对 tidyeval 的研究并不多。我个人更喜欢这个:

      library(data.table)
      DT <- as.data.table(df)
      lapply(c("Sex", "AgeGrouping", "Type"), 
             function(x) DT[, .(Total = sum(Number)), by = x])
      

      【讨论】:

        猜你喜欢
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        相关资源
        最近更新 更多