Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ddply to multiple columns equivalent in data.table

Tags:

r

data.table

plyr

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.

like image 244
Jonathan Avatar asked Sep 18 '13 15:09

Jonathan


1 Answers

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.

like image 82
Frank Avatar answered Oct 15 '22 15:10

Frank