Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine lists in R

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?

like image 357
Nairolf Avatar asked Jul 25 '13 06:07

Nairolf


People also ask

How do I combine multiple lists in R?

R provided two inbuilt functions named c() and append() to combine two or more lists. c() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.

How do I combine lists into a Dataframe in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.

How do I combine values in R?

The simplest way to group together values is with the function c() . Feel free to refer to this function however you like, but the words concatenate, combine, and collect are all good options.


1 Answers

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.

like image 168
Arun Avatar answered Oct 03 '22 22:10

Arun