[datatable-help] Is there a good way to do a self join in one line?

Chris Neff caneff at gmail.com
Wed Aug 3 14:43:41 CEST 2011


Say I want to calculate an aggregate statistic and append it to the
data frame all in one move. Like this:

DT <- data.table(x= 1:10, y=rep(1:2,each=5))

DT <- DT[, list(x, z=sum(x)), by=y]

This will append the new variable z to the data frame. But what if I
have a lot of columns, and I don't want to address them by name like I
did there? I'd like to do something like:


DT <- DT[, list(names(DT), z=sum(x)), by=y]

but that won't work because names(DT) is a character vector not the
parts of the list expression I want. I mean there is the following:

tmp <- DT[,list(z=sum(x)), by=y]

DT <- DT[tmp]

but creating a temporary variable is annoying.  This doesn't work:

DT <- DT[DT[, list(z=sum(x)), by=y]]

Thoughts?

Chris


More information about the datatable-help mailing list