Reputation: 3554
I have a data.table like:
foo <- data.table(a = c(1,2,3), b = c(4,5,6))
I want to add another column c which is by row/record a list of a
and b
. Something like:
data.table(a = c(1,2,3), b = c(4,5,6), c = c(list(1,4), list(2,5), list(3,6)))
but even in the example it only take one element and recycle
a b c
1: 1 4 1
2: 2 5 4
3: 3 6 2
4: 1 4 5
5: 2 5 3
6: 3 6 6
However I want:
a b c
1: 1 4 list(1,4)
2: 2 5 list(2,5)
3: 3 6 list(3,6)
I tried also:
foo$c <- foo[, list('a' = a, 'b' = b)]
foo$c <- foo[, list('a' = a, 'b' = b), by = 1:nrow(foo)]
foo$c <- as.list(foo[, list('a' = a, 'b' = b)])
Nothing works.
Upvotes: 1
Views: 513
Reputation: 215057
One way is to use Map
and list
:
foo[, c := Map(list, a, b)][]
# a b c
#1: 1 4 <list>
#2: 2 5 <list>
#3: 3 6 <list>
And column c
is a list of lists:
dput(foo$c)
# list(list(1, 4), list(2, 5), list(3, 6))
To keep the names:
foo[, c := Map(list, a=a, b=b)][]
# a b c
#1: 1 4 <list>
#2: 2 5 <list>
#3: 3 6 <list>
dput(foo$c)
# list(list(a = 1, b = 4), list(a = 2, b = 5), list(a = 3, b = 6))
Upvotes: 2
Reputation: 33548
Using list
instead of c
seems to work:
data.table(a = c(1,2,3), b = c(4,5,6), c = list(list(1,4), list(2,5), list(3,6)))
a b c
1: 1 4 <list>
2: 2 5 <list>
3: 3 6 <list>
Upvotes: 1