简体   繁体   English

如何将列表列表转换为列表数组?

[英]How to convert a list of lists to an array of lists?

I have a list of lists in R. I would like to convert it to an array of lists, but I only get an array of lists of lists: 我在R中有一个列表列表。我想将它转换为列表数组,但我只得到一个列表列表数组:

r <- list(list(a=1, b=NULL, c=NULL, d=1.23),
          list(a=2, b=NULL, c=NULL, d=3.32),
          list(a=3, b=NULL, c=NULL, d=2.13),
          list(a=4, b=NULL, c=NULL, d=3.25),
          list(a=5, b=NULL, c=NULL, d=0.14),
          list(a=6, b=NULL, c=NULL, d=5.13))
x <- array(r, dim=c(3,2))
x[1,1] # now a list of length 1 containing an element which is a list with components a--d

As you can see, x[1,1] (for example) is now a list of lists, but the "outer" list is useless. 如您所见, x[1,1] (例如)现在是列表列表,但“外部”列表是无用的。 I would rather like to have an array y with y[i,j] being x[i,j][[1]] . 我宁愿有一个数组yy[i,j]x[i,j][[1]] What's the best way to get this (using functions from base-R (no additional packages))? 获得此功能的最佳方式是什么(使用base-R中的函数(无附加软件包))?

I tried to use some unlist() hackery like array(unlist(r, recursive=FALSE), dim=c(3,2)) , but that fails. 我试图使用一些unlist() hackery像array(unlist(r, recursive=FALSE), dim=c(3,2)) ,但是失败了。 sapply(r, FUN=I) at least gives a matrix... maybe that helps (?) sapply(r, FUN=I)至少给出一个矩阵......也许这有助于(?)

使用双括号, x[[1,1]]

You can't do this, by design. 按设计你不能这样做。

Vector elements are by definition vectors of length 1, and arrays/matrices are still vectors with dimensions. 矢量元素是定义长度为1的向量,而数组/矩阵仍然是具有维度的向量。

Lists are themselves generic vectors, so they can be elements of other lists (or arrays, or matrices), but only if they themselves have length 1. 列表本身是通用向量,因此它们可以是其他列表(或数组或矩阵)的元素,但前提是它们本身的长度为1。

BTW this is the reason why using [ ] to select an object contained in a list only returns a list of size 1 containing the object, and not the actual object, which you need to get using [[ ]]. 顺便说一下,这就是为什么使用[]选择列表中包含的对象只返回包含对象的大小为1的列表,而不是使用[[]]需要获取的实际对象。

So the answer is, there's really no way to get rid of the "outer" list. 所以答案是,真的没有办法摆脱“外部”清单。

For details, consult the R Language Definition manual. 有关详细信息,请参阅R语言定义手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM