Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 列数据为2列的列表。表_R_Data.table - Fatal编程技术网

R 列数据为2列的列表。表

R 列数据为2列的列表。表,r,data.table,R,Data.table,我有一个data.table,如: foo <- data.table(a = c(1,2,3), b = c(4,5,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[, lis

我有一个data.table,如:

foo <- data.table(a = c(1,2,3), b = c(4,5,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)])

foo$c一种方法是使用
Map
list

foo[, c := Map(list, a, b)][]

#   a b      c
#1: 1 4 <list>
#2: 2 5 <list>
#3: 3 6 <list>
保留姓名:

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))
foo[,c:=Map(list,a=a,b=b)][]
#a、b、c
#1: 1 4 
#2: 2 5 
#3: 3 6 
dput(foo$c)
#列表(列表(a=1,b=4),列表(a=2,b=5),列表(a=3,b=6))

使用
列表
而不是
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>
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 
2: 2 5 
3: 3 6 

foo[,c:=(.BY)),BY=(a,b)]
@DavidArenburg-bang-on。如果你愿意,你可以给它一个答案。如果你想要一个向量而不是一个列表,有
foo[,c:=as.list(transpose(.SD)),.SDcols=a:b]
这与第三列的定义方式有关。调用
c
时,参数形成一个向量。在R中,可以有向量列表,但不能有列表向量。
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))
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>