mathlete
mathlete

Reputation: 6682

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 (?)

Upvotes: 3

Views: 3045

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

Use double brackets, x[[1,1]].

Upvotes: 5

Theodore Lytras
Theodore Lytras

Reputation: 3965

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.

Upvotes: 1

Related Questions