如何在r中将多个列转换为列表类型的列?

如何在r中将多个列转换为列表类型的列?,r,data.table,R,Data.table,我正在寻找一个数据帧(或数据表),例如 请注意,这与这里的问题不同,它返回一个不同形状的对象(我认为它只是一个普通的列表,每一行都是列表中的一项,而不是列表向量)您可以使用purrr::transpose(),它将向量列表转换为列表: dt[, combined := purrr::transpose(.(a,b,d))] dt # a b d combined #1: 1 NA NA <list> #2: 2 3 8 <list> #3: 4 5

我正在寻找一个数据帧(或数据表),例如


请注意,这与这里的问题不同,它返回一个不同形状的对象(我认为它只是一个普通的列表,每一行都是列表中的一项,而不是列表向量)

您可以使用
purrr::transpose()
,它将向量列表转换为列表:

dt[, combined := purrr::transpose(.(a,b,d))]

dt
#   a  b  d combined
#1: 1 NA NA   <list>
#2: 2  3  8   <list>
#3: 4  5 NA   <list>

combined = list(list(1,NA_real_,NA_real_),list(2,3,8),list(4,5,NA_real_))
identical(dt$combined, combined)
# [1] TRUE

要使@David的注释更明确,并将data.table方法推广到SE版本,它允许您将列名作为字符向量传递,并避免硬编码列名,您可以这样做,以了解更多有关SE与NSE的信息(您可以参考vignette(“NSE”):

这将命名所有子列表,但值对应于组合列表:


如果您不想使用任何函数:

dt[, combined := .(.(.SD)), by = 1:nrow(dt)]    
# because you want to transform each row to a list, normally you can group the data frame 
# by the row id, and turn each row into a list, and store the references in a new list 
# which will be a column in the resulted data.table

dt$combined
#[[1]]
#   a  b  d
#1: 1 NA NA

#[[2]]
#   a b d
#1: 2 3 8

#[[3]]
#   a b  d
#1: 4 5 NA

或者:
dt[,组合:=((a,b,d)),by=1:nrow(dt)]
这会让你更接近准确的期望输出。

我认为这个答案的大多数听众不知道SE是什么;可能需要解释或提供参考。@akrun,问题与您链接的问题不同。我想要一个数据框,其中列的类型是list,而不仅仅是list。(链接的答案返回一个列表,只需选中
dim(xy.list)
)它不是我。有人贴了可能的复制品,我给它贴了标签。这就是我所做的
dt[,combined := as.list(a,b,d)]
dt[,combined := do.call(list,list(a,b,d))]
dt[,combined := cbind(a,b,d)]
dt[,combined := lapply(list(a,b,d),list)]
dt[, combined := purrr::transpose(.(a,b,d))]

dt
#   a  b  d combined
#1: 1 NA NA   <list>
#2: 2  3  8   <list>
#3: 4  5 NA   <list>

combined = list(list(1,NA_real_,NA_real_),list(2,3,8),list(4,5,NA_real_))
identical(dt$combined, combined)
# [1] TRUE
dt[, combined := lapply(transpose(.(a,b,d)), as.list)]
identical(dt$combined, combined)
# [1] TRUE
dt[, combined := lapply(transpose(.SD), as.list), .SDcols = c("a","b","d")]
identical(lapply(dt$combined, setNames, NULL), combined)
# [1] TRUE
dt[, combined := .(.(.SD)), by = 1:nrow(dt)]    
# because you want to transform each row to a list, normally you can group the data frame 
# by the row id, and turn each row into a list, and store the references in a new list 
# which will be a column in the resulted data.table

dt$combined
#[[1]]
#   a  b  d
#1: 1 NA NA

#[[2]]
#   a b d
#1: 2 3 8

#[[3]]
#   a b  d
#1: 4 5 NA