【问题标题】:How to turn several columns into a column of type list in r?如何在r中将几列转换为列表类型的列?
【发布时间】:2017-06-08 14:03:13
【问题描述】:

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

dt <- data.table(a = c(1,2,4), b = c(NA,3,5), d = c(NA,8,NA))

变成一列的东西,比如

dt <- data.table(combined = list(list(1,NA,NA),list(2,3,8),list(4,5,NA))

以下都不起作用:

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

请注意,这与这里的问题data.frame rows to a list 不同,它返回一个不同形状的对象(我认为它只是一个普通列表,每一行作为列表中的一个项目,而不是列表的向量)

【问题讨论】:

  • @akrun ,问题与您链接的问题不同。我想要一个具有列表类型列的数据框,而不仅仅是列表。 (链接的答案返回一个列表,只需检查dim(xy.list)
  • 不是我。有人发布了可能重复的内容,我对其进行了重复标记。这就是我所做的一切

标签: r data.table


【解决方案1】:

您可以使用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

如果你不想使用额外的包,你可以使用data.table::transpose 加一点额外的努力:

dt[, combined := lapply(transpose(.(a,b,d)), as.list)]
identical(dt$combined, combined)
# [1] TRUE

为了使@David 的评论更明确,并将 data.table 方法推广到 SE 版本,它允许您将列名称作为字符向量传递并避免对列名称进行硬编码,您可以这样做,以了解有关 SE 与NSE(可以参考vignette("nse")):

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

或者:dt[, combined := .(.(.(a,b,d))), by = 1:nrow(dt)],它可以让您更接近所需的输出。

【讨论】:

  • 我认为这个答案的大多数观众都不知道 SE 是什么;可能想解释或提供参考。
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多