Combine lists in R

Florian picture Florian · Jul 25, 2013 · Viewed 7.5k times · Source

What would be an easy and fast way to get from:

x <- list(a1=2, b1=c(1,2), c1=1:3)
y <- list(a2=5, b2=c(2,5), c2=2:4)

to

list(list(x$a1, y$a2), list(x$b1, y$b2), list(x$c1, y$c2))

?

Or in general:

If list x and y have same length and their elements also correspond in length, how can it be combined to a single list as shown above?

Answer

Arun picture Arun · Jul 25, 2013

An easy way would be to use mapply as follows:

mapply(x, y, FUN=list, SIMPLIFY=FALSE)

Not sure if it's the fastest though. You can replace x and y with unname(x) and unname(y) if you don't want names in your output.