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 rbind every nth element of a list using base R?

I have a list containing different dataframes. Every nth dataframe of the list has the same structure. The list is somewhat like this:

my_list <- list(list(data.frame(a= rnorm(10), b= rnorm(10)),
                 data.frame(abc= letters[1:10])),
                list(data.frame(a= rnorm(10), b= rnorm(10)),
                 data.frame(abc= letters[11:20])))

I want to rbind.data.frame the first dataframe of each list and the second dataframe of each list. Thus, my expected result is:

list(rbind.data.frame(my_list[[1]][[1]], my_list[[2]][[1]]),
     rbind.data.frame(my_list[[1]][[2]], my_list[[2]][[2]]))

In this example there are two dataframes per list but in my case the number of dataframes can change while running the code another time. So I need a general solution that binds every nth list. How can I do this with base R? It must be base R.

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 :

Select the element that you’re interested in with something like

lapply(my_list, `[[`, 1)

for the first data.frame. Then use do.call() to rbind the list of selected data.frames

do.call(rbind, lapply(my_list, `[[`, 1))

Generalize this with a function that extracts any list element i

FUN <- function(x, i)
    do.call(rbind, lapply(x, `[[`, i))

and use lapply() to generate the multiple data.frames you’re interested in

lapply(1:2, FUN, x = my_list)
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