r - 聚合并计算 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"))
>
解决方案
玩具例子,不是最优雅的方式
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
推荐阅读
- amp-html - Prebid RTC AMP 用户同步分析 iframe 错误
- swift - 出现错误:-无法读取数据,因为它在 Swift 中使用 Alamofire 和 Codable 的格式不正确
- java - Azure Functions,“System.Private.CoreLib:值不能为空。(参数'path1')。值不能为空。(参数'provider')”
- java - 我如何使用 InCombiningDiacriticalMarks 忽略一个案例
- javascript - Vue js在子组件之间发送图像blob并显示图像预览
- python - 将值附加到嵌套字典中的列表
- flutter - Flutter Web:读取和写入查询字符串值
- php - PHP:我在数据库中插入 1 条记录,但它自动插入 2
- javascript - 将 Object.entries() 减少为字符串并获得随机逗号
- ruby-on-rails - 如何编写远程请求规范?