Reputation: 3062
I have the following data table:
library(data.table)
dat = data.table(j = c(3,8,9,11,10,28, 5), gr = c(9,9,9,9,10,10, 10), day = c(1,1,2,2,1,1,2))
> dat
j gr day
1: 3 9 1
2: 8 9 1
3: 9 9 2
4: 11 9 2
5: 10 10 1
6: 28 10 1
7: 5 10 2
I would like for each group (gr column) and day to create a vector with all the available values in j.
I have tried the following to no avail:
dat[, j[1:.N], by = .(gr, day )]
dat[, list(j[1:.N]), by = .(gr, day )]
This partially works but I would need to do some further manipulations to get the desired result:
dat[, list(list(Reduce(c, j, accumulate = T))), by = .(gr, day )]
My ideal result would look like:
> res_dat
gr day all_values
1: 9 1 3,8
2: 9 2 9,11
3: 10 1 10,28
4: 10 2 5
I do not want this to be a string, I want it to be a list of vectors so this answer data table string concatenation of SD columns for by group values is not applicable.
Upvotes: 2
Views: 854
Reputation: 886968
We need a list
column. The .(
is a concise syntax for list(
in data.table
.
dat[, .(j = .(j)), by = .(gr, day)]
-output
gr day j
1: 9 1 3,8
2: 9 2 9,11
3: 10 1 10,28
4: 10 2 5
i.e. it can be otherwise written as
dat[, list(j = list(j)), .(gr, day)]
gr day j
1: 9 1 3,8
2: 9 2 9,11
3: 10 1 10,28
4: 10 2 5
Upvotes: 4