【问题标题】:Grouping & summarizing data frame by multiple different columns in R通过 R 中的多个不同列对数据框进行分组和汇总
【发布时间】:2016-02-15 16:21:09
【问题描述】:

我不知道我是否没有使用正确的术语进行搜索,但我找不到关于此的帖子。

我有一个 df :

df <- data.frame(grouping_letter = c('A', 'A', 'B', 'B', 'C', 'C'), grouping_animal = c('Cat', 'Dog', 'Cat', 'Dog', 'Cat', 'Dog'), value = c(1,2,3,4,5,6))

我想按grouping_lettergrouping_animal 分组。我想使用dplyr 来执行此操作。

如果我单独做的话,那就是:

df %>% group_by(grouping_letter) %>% summarise(sum(value))

df %>% group_by(grouping_animal) %>% summarise(sum(value))

现在假设我有数百个列需要单独分组。我怎样才能做到这一点?

我在尝试:

results <- NULL for (i in grouping_columns) { results[[i]] <- df %>% group_by(df$i) %>% summarize(sum(value)) }

我得到了一个名为 results 的列表和输出。我想知道是否有更好的方法来代替使用 for 循环?

【问题讨论】:

    标签: r dplyr apply group-summaries


    【解决方案1】:

    我们可以创建一个'分组'列的索引(使用grep),循环索引(使用lapply)并在'索引中的列分组后分别获取'值'的sum '。

     library(dplyr)
     i1 <- grep('grouping', names(df))
     lapply(i1, function(i) 
            df[setdiff(seq_along(df), i)] %>% 
                         group_by_(.dots=names(.)[1]) %>% 
                         summarise(Sumvalue= sum(value)))
    #[[1]]
    #Source: local data frame [2 x 2]
    
    #  grouping_animal Sumvalue
    #           (fctr)    (dbl)
    #1             Cat        9
    #2             Dog       12
    
    #[[2]]
    #Source: local data frame [3 x 2]
    
    #  grouping_letter Sumvalue
    #           (fctr)    (dbl)
    #1               A        3
    #2               B        7
    #3               C       11
    

    或者我们可以通过将数据集从“宽”格式转换为“长”格式,然后按相关列分组并获取“值”的sum

    library(tidyr)
    gather(df, Var, Group, -value) %>% 
             group_by(Var, Group) %>% 
             summarise(Sumvalue = sum(value))
    #              Var Group Sumvalue
    #            (chr) (chr)    (dbl)
    #1 grouping_animal   Cat        9
    #2 grouping_animal   Dog       12
    #3 grouping_letter     A        3
    #4 grouping_letter     B        7
    #5 grouping_letter     C       11
    

    【讨论】:

    • 我在 11M 行、12 个值 cols 和 6 个分组变量的 df 上尝试它。以非常长的循环完成速度要快得多!
    • @vagabond 然后,与循环方法相比,从“宽”转换为“长”可能需要一些时间。您是否尝试过lapply 选项?
    • 还没有。 .我知道它会射击记忆!我在 8GB 内存 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多