【问题标题】:R: Sum specific columns grouped by a particular column [duplicate]R:对按特定列分组的特定列求和[重复]
【发布时间】:2020-02-19 19:00:32
【问题描述】:

我有一个如下所示的数据框:

Col1 Col2 Col3 Col4 
10    A    5    4    
10    A    6    3   
30    B    2    7   
45    C    5    1  
45    C    2    1   

我想将仅按 Col2 分组的第 3 列和第 4 列相加,这样我的结果数据框看起来像

Col1 Col2 Col3 Col4 
10    A    11    7    
30    B    2     7   
45    C    7     2  

Col1 是 Col2 的标识符,所以我希望保留它。谢谢

【问题讨论】:

标签: r


【解决方案1】:

1.最小可重复的示例数据:

df <- structure(list(Col1 = c(10L, 10L, 30L, 45L, 45L),
                     Col2 = c("A", "A", "B", "C", "C"), 
                     Col3 = c(5L, 6L, 2L, 5L, 2L),
                     Col4 = c(4L, 3L, 7L, 1L, 1L)),
                row.names = c(NA, -5L), class = "data.frame")

2.使用dplyr的解决方案

library(dplyr)

df %>%
group_by(Col1, Col2) %>%
summarise(Col3 = sum(Col3),
          Col4 = sum(Col4))

返回:

   Col1 Col2   Col3  Col4
  <int> <chr> <int> <int>
1    10 A        11     7
2    30 B         2     7
3    45 C         7     2

【讨论】:

    【解决方案2】:

    您可以使用aggregate。由于Col1Col2标识符,它可以与Col2 一起用于分组。

    aggregate(.~Col1+Col2, df, sum)
    #  Col1 Col2 Col3 Col4
    #1   10    A   11    7
    #2   30    B    2    7
    #3   45    C    7    2
    

    或者你可以使用rowsummatchcbind

    x <- rowsum(df[c("Col3","Col4")], df$Col2)
    cbind(df[match(rownames(x), df$Col2), c("Col1","Col2")], x)
    #  Col1 Col2 Col3 Col4
    #1   10    A   11    7
    #3   30    B    2    7
    #4   45    C    7    2
    

    【讨论】:

      【解决方案3】:

      如果您只想按Col2 分组并保留Col1,也许您可​​以使用基R 中的aggregate + merge,如下所示

      dfout <- merge(unique(df[1:2]),aggregate(.~Col2,df[-1],sum))
      

      这样

      > dfout
        Col2 Col1 Col3 Col4
      1    A   10   11    7
      2    B   30    2    7
      3    C   45    7    2
      

      【讨论】:

        猜你喜欢
        • 2015-02-23
        • 2016-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 2022-06-20
        相关资源
        最近更新 更多