ddply到data.table中等效的多个列

时间:2021-05-24 09:16:41

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:

我是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))

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:

我想要做的是在多个列之间求和,而不必手动指定列名。 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)}]), ]

To be explicit, my question is "is there a way to do the equivalent of the ddply code in data.table?"

明确地说,我的问题是“有没有办法在data.table中执行等效的ddply代码?”

Any help is greatly appreciated, thanks.

非常感谢任何帮助,谢谢。

1 个解决方案

#1


7  

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.

这在data.table的FAQ的2.1节中提到。

#1


7  

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.

这在data.table的FAQ的2.1节中提到。