Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - How to rbind two lists while alternating their list elements

Tags:

r

I'd like to know how to rbind two lists containing vectors into a data frame. e.g.

a<-list(c(1,2,3,4,5), c(2,3,4,5,6))
b<-list(c(3,4,5,6,7), c(4,5,6,7,8))

How to make a data frame from the two lists as the following:

1 2 3 4 5
3 4 5 6 7
2 3 4 5 6 
4 5 6 7 8

So I need to take the first element of each list and then rbind them. Then take the second element of each list and then rbind to the previous data frame. I know I could use a for loop but is there a better and faster way to do this?

like image 743
Josh Avatar asked Oct 23 '25 00:10

Josh


2 Answers

A variation on @DiscoSuperfly's answer that will work with objects of uneven length, like:

a <- list(c(1,2,3,4,5), c(2,3,4,5,6), c(1,1,1,1,1))
b <- list(c(3,4,5,6,7), c(4,5,6,7,8))

An answer:

L <- list(a,b)
L <- lapply(L, `length<-`, max(lengths(L)))
do.call(rbind, do.call(Map, c(rbind, L)))

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    3    4    5    6    7
#[3,]    2    3    4    5    6
#[4,]    4    5    6    7    8
#[5,]    1    1    1    1    1
like image 67
thelatemail Avatar answered Oct 25 '25 14:10

thelatemail


A solution using the purrr package.

library(purrr)
map2_dfr(a, b, ~data.frame(rbind(.x, .y)))

  X1 X2 X3 X4 X5
1  1  2  3  4  5
2  3  4  5  6  7
3  2  3  4  5  6
4  4  5  6  7  8
like image 42
www Avatar answered Oct 25 '25 13:10

www



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!