Bing Cui Bing Cui - 1 month ago 4x
R Question

Group by ID, each element of the new table is a vector

I have a table like this

data.table(ID = c(1,2,3,4,5,6),
R = c("s","s","n","n","s","s"),
S = c("a","a","a","b","b","b"))

and I'm trying to get this result

a b
s 1, 2 5, 6
n 3 4

Is there any option in data.table can do this?


You can use dcast from reshape2 with the appropriate aggregating function:


dcast(df, R~S, value.var='ID', fun.aggregate=Curry(paste0, collapse=','))
#  R   a   b
#1 n   3   4
#2 s 1,2 5,6

Or even short as @akrun underlined:

dcast(df, R~S, value.var='ID', toString)