Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i combine rowise data frames within a list?

Suppose I have the following two lists. I want to take the first entry of list2 and combine this data frame to list1. Doing this for all entries.

data1 <- data.frame(id = 1:6,                                  
                    x1 = c(5, 1, 4, 9, 1, 2),
                    x2 = c("A", "Y", "G", "F", "G", "Y"))
data2 <- data.frame(id = 4:9,                                  
                    y1 = c(3, 3, 4, 1, 2, 9),
                    y2 = c("a", "x", "a", "x", "a", "x"))
l1 <- list(data1, data2)
l2 <- list(data1, data2)

What I expect as a result is one list of length 2. Each entry should be a data frame with 12 rows and 3 columns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We may use Map with rbind to rbind the corresponding data.frame elements from both lists

Map(rbind, l1, l2)

-output

[[1]]
   id x1 x2
1   1  5  A
2   2  1  Y
3   3  4  G
4   4  9  F
5   5  1  G
6   6  2  Y
7   1  5  A
8   2  1  Y
9   3  4  G
10  4  9  F
11  5  1  G
12  6  2  Y

[[2]]
   id y1 y2
1   4  3  a
2   5  3  x
3   6  4  a
4   7  1  x
5   8  2  a
6   9  9  x
7   4  3  a
8   5  3  x
9   6  4  a
10  7  1  x
11  8  2  a
12  9  9  x

Or using map2 from purrr

library(purrr)
library(dplyr)
map2(l1, l2, bind_rows)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading