Aggregate data frame while keeping original order, in a simple manner

前端 未结 4 1020
囚心锁ツ
囚心锁ツ 2021-02-15 12:38

I\'m having some trouble aggregating a data frame while keeping the groups in their original order (order based on first appearance in data frame). I\'ve managed to get it right

4条回答
  •  庸人自扰
    2021-02-15 13:01

    A bit tough to read, but it gives you what you want and I added some comments to clarify.

    # Define the columns you want to combine into the grouping variable
    sel.col <- grepl("^sel", names(orig.df))
    # Create the grouping variable
    lev <- apply(orig.df[sel.col], 1, paste, collapse=" ")
    # Split and sum up
    data.frame(unique(orig.df[sel.col]),
               t(sapply(split(orig.df[!sel.col], factor(lev, levels=unique(lev))),
                        apply, 2, sum)))
    

    The output looks like this

       sel.1 sel.2 add.1 add.2
    1      5     4    96    84
    2      2     2   175   176
    3      1     5   384   366
    5      2     5    95    89
    6      4     1   174   192
    7      2     4    82    87
    8      5     3    91    98
    10     3     2   189   178
    11     1     4   170   183
    14     1     1   100    91
    17     3     3    81    82
    19     5     5    83    88
    20     2     3    90    96
    

提交回复
热议问题