Aggregating across list of dataframes and storing all results

后端 未结 1 887
梦毁少年i
梦毁少年i 2021-01-16 10:40

I have a list of 9 data frames, each data frame having approx 100 rows and 5-6 cols.

I want to aggregate the values in a col based on the groups specified in anothe

1条回答
  •  执笔经年
    2021-01-16 11:39

    In R, there are many efficiently implemented functions 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 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"))
    

    0 讨论(0)
提交回复
热议问题