Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create data.table listing values of one variable grouped by another variable

I would like to create a data.table of the form

newdat
#       A     B
#    1: 1   1,2
#    2: 2 1,2,3

from a data.table of the form

dat <- data.table(A = c(1, 1, 2, 2, 2), B = c(1, 2, 1, 2, 3))
dat
#    A B
# 1: 1 1
# 2: 1 2
# 3: 2 1
# 4: 2 2
# 5: 2 3

I can create newdat directly via

newdat <- data.table(A = 1:2, B = list(1:2, 1:3))

and I guess I could fill in the necessary arguments via something like

newdat <- data.table(A = unique(dat$A), B = split(dat$B, dat$A))

but I have a feeling there is a better way to do this using the data.table functionality that I can't find right now - any suggestions?

like image 753
Heather Turner Avatar asked Sep 10 '13 14:09

Heather Turner


1 Answers

Here you go dat[,list(B=list(B)),by=A]

dat[,list(B=list(B)),by=A]
   A     B
1: 1   1,2
2: 2 1,2,3
like image 132
statquant Avatar answered Nov 04 '22 15:11

statquant