Reputation: 2489
I am trying to write code, preferably using data.table
, to group data by id
from a list column with ranges (my_range
) into a new aggregate dataset with a column (union_of_my_range
) containing the union of my_range
for each id.
library(data.table)
#Input
d <- data.table(id=c(1,1,2,2),
my_range=list(1:5,2:6,3:7,9:9)
)
#Desired output:
g <- data.table(id=c(1,2),
union_of_my_range=list(c(1:5,6),c(3:7,9))
)
Preferably looking for a data.table
solution,
This is what I have thus far:
d[, .(my_range_union = SOMETING unon my_range ) ,id]
but I am not able to keep track of all the lists interacting in the aggregation step
Upvotes: 1
Views: 138
Reputation: 887391
We can use Reduce
with union
d[, .(my_range_union = list(Reduce(union, my_range))), id]
# id my_range_union
#1: 1 1,2,3,4,5,6
#2: 2 3,4,5,6,7,9
Upvotes: 1
Reputation: 389065
You can unlist
my_range
values, gather unique
values and put it in a new list.
library(data.table)
d[, .(my_range_union = list(unique(unlist(my_range)))) ,id]
# id my_range_union
#1: 1 1,2,3,4,5,6
#2: 2 3,4,5,6,7,9
Upvotes: 1