Maiasaura
Maiasaura

Reputation: 32986

How do I combine lists of identical lengths into one?

Assuming I have two lists:

 xx <- as.list(1:3)
 yy <- as.list(LETTERS[1:3])

How do I combine the two such that each element of the new list is a list of the corresponding elements of each component list. So if I combined the two above, I should get:

> combined_list
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] "a"


[[2]]
[[2]][[1]]
[1] 2

[[2]][[2]]
[1] "b"


[[3]]
[[3]][[1]]
[1] 3

[[3]][[2]]
[1] "c"

If you can suggest a solution, I'd like to scale this to 3 or more.

Upvotes: 3

Views: 1017

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162401

This should do the trick. Nicely, mapply() will take an arbitrary number of lists as arguments.

xx <- as.list(1:3)
yy <- as.list(LETTERS[1:3])
zz <- rnorm(3)

mapply(list, xx, yy, zz, SIMPLIFY=FALSE)

Upvotes: 6

Related Questions