Martin
Martin

Reputation: 175

R data.table group by range of columns

I am trying to group the R data.table according to a range of columns. Without success so far. Is there any easy way how to do it?

Example:

library(data.table)

id <- c(1:1000) 
x1 <- sample(1:10, 1000, replace=T)
x2 <- sample(1:10, 1000, replace=T)
x3 <- sample(1:10, 1000, replace=T)
x4 <- sample(1:10, 1000, replace=T)
x5 <- sample(1:10, 1000, replace=T)

df<-data.frame(id,x1,x2,x3,x4,x5)
dt<-data.table(df)

dt[,.N,by=list(x1,x2,x3,x4,x5)]

Now I would like to use something like

dt[,.N,by=list(x1:x5)]  

but it, of course, does not work. Do I miss a relatively simple approach to this problem?

Upvotes: 1

Views: 166

Answers (1)

mtoto
mtoto

Reputation: 24188

We could use paste0():

dt[, .N, by = c(paste0("x", 1:5))]

Upvotes: 4

Related Questions