簡體   English   中英

作為列data.table的2列的列表

[英]List of 2 columns as column data.table

我有一個data.table喜歡:

foo <- data.table(a = c(1,2,3), b = c(4,5,6))

我想添加另一列c,它是按行/記錄ab的列表。 就像是:

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)])

什么都行不通。

一種方法是使用Maplist

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM