[英]List of 2 columns as column data.table
我有一個data.table喜歡:
foo <- data.table(a = c(1,2,3), b = c(4,5,6))
我想添加另一列c,它是按行/記錄a
和b
的列表。 就像是:
data.table(a = c(1,2,3), b = c(4,5,6), c = c(list(1,4), list(2,5), list(3,6)))
但即使在這個例子中,它只需要一個元素並循環使用
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
不過我想:
a b c
1: 1 4 list(1,4)
2: 2 5 list(2,5)
3: 3 6 list(3,6)
我也嘗試過:
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)])
什么都行不通。
一種方法是使用Map
和list
:
foo[, c := Map(list, a, b)][]
# a b c
#1: 1 4 <list>
#2: 2 5 <list>
#3: 3 6 <list>
列c
是列表列表:
dput(foo$c)
# list(list(1, 4), list(2, 5), list(3, 6))
保留名稱:
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))
使用list
而不是c
似乎工作:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.