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 to merge datasets in a list by rows in R?

Similar questions have been asked here and here and here. However, none seem to help my specific situation. Im trying to merge a bunch of datasets (that are in a list) and turn it into a matrix. But Im trying to merge them by row. So, for example, if we have some data that looks like this:

set.seed(100)

dfList <- NULL
for(i in 1:3){
  dfList[[i]] <- data.frame(
    x1 = sample(1:10, 3, replace = T),
    x2 = sample(1:10, 3, replace = T)
    )
}

> dfList
[[1]]
  x1 x2
1 10  3
2  7  9
3  6 10

[[2]]
  x1 x2
1  7  4
2  6  7
3  6  6

[[3]]
  x1 x2
1  2  7
2  7  8
3  7  2

I am trying to merge the datasets by row and turn it into a matrix. What I mean is, the 1st row of my new matrix will come from the 1st row of the 1st data frame in the list. The 2nd row of my new matrix will come from the 1st row of the 2nd data frame in the list… and so on.

So, using the above example, my desired output would look like:

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

      x1 x2
 [1,] 10  3
 [2,]  7  4
 [3,]  2  7
 [4,]  7  9
 [5,]  6  7
 [6,]  7  8
 [7,]  6 10
 [8,]  6  6
 [9,]  7  2

Any suggestions as to how I could do this?

>Solution :

You can do:

library(tidyverse)
new_matrix <- lapply(seq_along(dfList),
                     function(x) {dfList[[x]] <- dfList[[x]] %>% mutate(id1 = 1:n(), id2 = x)}) %>%
  bind_rows() %>%
  arrange(id1, id2) %>%
  select(-id1, -id2) %>%
  as.matrix()



     x1 x2
 [1,] 10  3
 [2,]  7  4
 [3,]  2  7
 [4,]  7  9
 [5,]  6  7
 [6,]  7  8
 [7,]  6 10
 [8,]  6  6
 [9,]  7  2
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