【问题标题】:aggregate data frame with many columns according to one column [duplicate]根据一列聚合具有多列的数据框[重复]
【发布时间】:2017-06-30 16:31:51
【问题描述】:

从多列的数据框中,我想通过一列聚合(即sum)数百列,而不指定每个列名。

一些样本数据:

names <- floor(runif(20, 1, 5))
sample <- cbind(names)

for(i in 1:20){
col <- rnorm(20,2,4)
sample <- cbind(sample, col)
}

到目前为止,我所拥有的是以下代码,但它告诉我参数的长度必须相同。

aggregated <- aggregate.data.frame(sample[,c(2:20)], by = as.list(names),     FUN = 'sum')

原始数据集要大得多,所以我无法指定要聚合的每一列的名称,也无法使用列表函数。

【问题讨论】:

    标签: r dataframe aggregate


    【解决方案1】:

    您实际上根本不需要列出它们:

    aggregate(. ~ names, sample, sum) # . represents all other columns
    

    当然base R是我最喜欢的,但如果有人想要dplyr

    library(dplyr)
    data.frame(sample) %>% 
                 group_by(names) %>% 
                 summarise_each(funs(sum))
    

    【讨论】:

      【解决方案2】:

      只需稍微修改您的代码:

      aggregated &lt;- aggregate(sample[,c(2:20)], by = list(names), FUN = 'sum')

      【讨论】:

        猜你喜欢
        • 2017-10-29
        • 2019-10-08
        • 2021-11-21
        • 2019-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-27
        • 2018-07-28
        相关资源
        最近更新 更多