首页 > 解决方案 > 聚合并计算 r 中的相同行

问题描述

我有一个看起来像这样的data.frame(但是有更多的列和行): 在此处输入图像描述

我想对所有列相同的行求和并创建最后一列“count”,以获得如下结果: 在此处输入图像描述

谢谢你的帮助!

数据:

structure(list(Gene = c("A", "A", "B", "C"), `Cell 1` = c(2, 
2, 3, 4), `Cell 2` = c(2, 2, 3, 4), `Cell 3` = c(2, 2, 3, 4)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))
> 

标签: rgroup-byaggregate

解决方案


玩具例子,不是最优雅的方式

mtcars2=mtcars[c(1,1,2,3),]

do.call(rbind,
  by(
    mtcars2,
    mtcars2,
    function(x){
      data.frame(unique(x),"Count"=nrow(x))
    })
)

               mpg cyl disp  hp drat    wt  qsec vs am gear carb Count
Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1     1
Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4     2
Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4     1

编辑: OP提供的数据

df=structure(list(Gene = c("A", "A", "B", "C"), `Cell 1` = c(2, 
                                                          2, 3, 4), `Cell 2` = c(2, 2, 3, 4), `Cell 3` = c(2, 2, 3, 4)), row.names = c(NA, 
                                                                                                                                       -4L), class = c("tbl_df", "tbl", "data.frame"))
do.call(rbind,
  by(df,
     df,
     function(x){
       data.frame(unique(x),"Count"=nrow(x))
     }
  )
)

  Gene Cell.1 Cell.2 Cell.3 Count
1    A      2      2      2     2
3    B      3      3      3     1
4    C      4      4      4     1

推荐阅读