ddply到data.table中等效的多列 [英] ddply to multiple columns equivalent in data.table
问题描述
我是data.table软件包的忠实拥护者,并且在将plyr软件包的ddply中的某些代码转换为data.table中的等效代码时遇到了麻烦. ddply的代码是:
dfx <- data.frame(
group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
sex = sample(c("M", "F"), size = 29, replace = TRUE),
age = runif(n = 29, min = 18, max = 54),
age2 = runif(n = 29, min = 18, max = 54)
)
ddply(dfx, .(group, sex), numcolwise(sum))
我想做的是跨多个列求和,而不必手动指定列名. data.table包中的等效手册是:
dfx.dt = data.table(dfx)
dfx.dt[ , sum.age := sum(age), by="group,sex"]
dfx.dt[ , sum.age2 := sum(age2), by="group,sex"]
dfx.dt[!duplicated(dfx.dt[ , {list(group, sex)}]), ]
明确地说,我的问题是是否有办法等效于data.table中的ddply代码?"
非常感谢您的帮助.
是的,有一种方法:
dfx.dt[,lapply(.SD,sum),by='group,sex']
有关data.table的常见问题解答的2.1节中提到了这一点. /p>
I am a big fan of the data.table package and I am having trouble converting some code in ddply of the plyr package into the equivalent in a data.table. The code for ddply is:
dfx <- data.frame(
group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
sex = sample(c("M", "F"), size = 29, replace = TRUE),
age = runif(n = 29, min = 18, max = 54),
age2 = runif(n = 29, min = 18, max = 54)
)
ddply(dfx, .(group, sex), numcolwise(sum))
What I want to do is sum across multiple columns without having to manually specify the column names. The manual equivalent in the data.table package is:
dfx.dt = data.table(dfx)
dfx.dt[ , sum.age := sum(age), by="group,sex"]
dfx.dt[ , sum.age2 := sum(age2), by="group,sex"]
dfx.dt[!duplicated(dfx.dt[ , {list(group, sex)}]), ]
To be explicit, my question is "is there a way to do the equivalent of the ddply code in data.table?"
Any help is greatly appreciated, thanks.
Yes, there's a way:
dfx.dt[,lapply(.SD,sum),by='group,sex']
This is mentioned in section 2.1 of the FAQ for data.table.
这篇关于ddply到data.table中等效的多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!