简体   繁体   中英

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 <- 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. I would rather like to have an array y with y[i,j] being x[i,j][[1]] . What's the best way to get this (using functions from base-R (no additional packages))?

I tried to use some unlist() hackery like array(unlist(r, recursive=FALSE), dim=c(3,2)) , but that fails. sapply(r, FUN=I) at least gives a matrix... maybe that helps (?)

使用双括号, 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.

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.

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 [[ ]].

So the answer is, there's really no way to get rid of the "outer" list.

For details, consult the R Language Definition manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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