汇总数据框列表并存储所有结果

时间:2017-08-04 18:57:42

标签: r dataframe aggregate

我有一个包含9个数据帧的列表,每个数据帧有大约100行和5-6列。

我希望根据所有数据框中另一个col中指定的组聚合col中的值,并将所有结果存储在单独的数据框中。为了阐明,请考虑一个列表

    [[1]]  
    Date  Group  Age
    Nov     A    13
    Nov     A    14
    Nov     B    9
    Nov     D    10
    [[2]]
    Date  Group  Age
    Dec     C    11
    Dec     C    12
    Dec     E    10

我的代码如下

for (i in 1:length(list)){
x<-aggregate(list[[i]]$Age~list[[i]]$Group, list[[i]], sum)
x<-rbind(x)
}

但最后,x只包含数据帧2的聚合结果(因为i = 2)而不包含数据帧1的聚合结果,尽管我试图绑定结果。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

In R, there are many efficiently implemented function which help to avoid the hassle of writing for loops.

In his comment, S Rivero has suggested to use lapply() instead of a for loop and to rbind() the aggregates later:

do.call(rbind, lapply(dflist, function(x) aggregate(Age ~ Group, x, sum)))

My suggestion is, to combine the data.frames first and then to compute the aggregates using data.table:

library(data.table)
rbindlist(dflist)[, sum(Age), by = Group]
   Group V1
1:     A 27
2:     B  9
3:     D 10
4:     C 23
5:     E 10

Data

dflist <- list(structure(list(Date = c("Nov", "Nov", "Nov", "Nov"), Group = c("A", 
"A", "B", "D"), Age = c(13L, 14L, 9L, 10L)), .Names = c("Date", 
"Group", "Age"), row.names = c(NA, -4L), class = "data.frame"), 
    structure(list(Date = c("Dec", "Dec", "Dec"), Group = c("C", 
    "C", "E"), Age = c(11L, 12L, 10L)), .Names = c("Date", "Group", 
    "Age"), row.names = c(NA, -3L), class = "data.frame"))
相关问题