无论是在此处还是在 Google 上,我都无法使用搜索功能找到问题的答案。
我有一个数据框(500 列宽,200.000 行长),每个人有多行。每个单元格(除了具有人员 ID 的第一列)都包含 0 或 1。我正在寻找一种方法将此数据框减少到每人 1 行,其中我按人取每列的最大值。
我知道我可以使用 ddply 或 data.table...如下所示...
tt <-data.frame(person=c(1,1,1,2,2,2,3,3,3), col1=c(0,0,1,1,1,0,0,0,0),col2=c(1, 1, 0, 0, 0, 0, 1 ,0 ,1))
library(plyr)
ddply(tt, .(person), summarize, col1=max(col1), col2=max(col2))
person col1 col2
1 1 1
2 1 0
3 0 1
但我不想指定我的每个列名称,因为 1) 我有 500 和 2) 在新数据集上它们可能不同。
最佳答案
使用 dplyr
中的 summarise_each
函数
library(dplyr)
tt %>% group_by(person) %>% summarise_each(funs(max))
# person col1 col2
# 1 1 1 1
# 2 2 1 0
# 3 3 0 1
或者只是基本的聚合
函数
aggregate(.~person, tt, max)
# person col1 col2
# 1 1 1 1
# 2 2 1 0
# 3 3 0 1
关于R 在不指定列名的情况下聚合大量列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787428/