我想对这些数据进行分组,但在分组时对某些列应用不同的函数。
ID type isDesc isImage
1 1 1 0
1 1 0 1
1 1 0 1
4 2 0 1
4 2 1 0
6 1 1 0
6 1 0 1
6 1 0 0
我要分组
ID
, 列 isDesc
和 isImage
可以求和,但我想按原样获得 type 的值。 type
整个数据集都是一样的。结果应如下所示:ID type isDesc isImage
1 1 1 2
4 2 1 1
6 1 1 1
目前我正在使用
library(plyr)
summarized = ddply(data, .(ID), numcolwise(sum))
但它只是总结了所有列。您不必使用
ddply
但如果你认为这对这份工作有好处,我想坚持下去。 data.table
图书馆也是一种选择
最佳答案
使用 data.table
:
require(data.table)
dt <- data.table(data, key="ID")
dt[, list(type=type[1], isDesc=sum(isDesc),
isImage=sum(isImage)), by=ID]
# ID type isDesc isImage
# 1: 1 1 1 2
# 2: 4 2 1 1
# 3: 6 1 1 1
使用
plyr
:ddply(data , .(ID), summarise, type=type[1], isDesc=sum(isDesc), isImage=sum(isImage))
# ID type isDesc isImage
# 1 1 1 1 2
# 2 4 2 1 1
# 3 6 1 1 1
编辑:使用
data.table
的 .SDcols
,如果您有太多要求和的列,而其他列只取第一个值,则可以执行此操作。dt1 <- dt[, lapply(.SD, sum), by=ID, .SDcols=c(3,4)]
dt2 <- dt[, lapply(.SD, head, 1), by=ID, .SDcols=c(2)]
> dt2[dt1]
# ID type isDesc isImage
# 1: 1 1 1 2
# 2: 4 2 1 1
# 3: 6 1 1 1
您可以提供列名或列号作为 .SDcols 的参数。例如:
.SDcols=c("type")
也是有效的。
关于R - 分组数据但对不同的列应用不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434123/