Search code examples
rlistbind

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.


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)