R 在不指定列名的情况下聚合大量列

标签 r dataframe aggregate

无论是在此处还是在 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/

相关文章:

r - 从列表中提取输出并保存在数据框中

python - 如何使用pandas弹出导致错误的日期记录?

python - groupby(pd.TimeGrouper ('time_interval' )).idxmin() 错误生成的空数据帧

r - 下载 WorldPop 人口计数栅格

sql - 多次聚合多行

r - 使用 ggplot() 更改线条颜色

R ggplot2 : colouring step plot depending on value

读取具有 Col :ColData 等数据的文本文件

dataframe - 如何按组将方程式应用于 Pandas 数据框

带有字符串值的 mysql 数据透视表