Search code examples
rlistbindnested-lists

Bind data frames from two nested lists by list and df names


I would like to bind R data frames from two different nested lists by its names as follows:


list1 = list(list_a = list(df1 = data.frame(letters = c('A','B','C'),
                                            numbers = seq(1,3)),
                           
                           df2 = data.frame(letters = c('A','B','C','D','E'),
                                            numbers = seq(1,5))),
             
             list_b = list(df3 = data.frame(norm = rnorm(4))))



list2 = list(list_a = list(df1 = data.frame(letters = c('D','E','F'),
                                            numbers = seq(4,6)),
                           
                           df2 = data.frame(letters = c('F','G','H','I','J'),
                                            numbers = seq(6,10))),
             
             list_b = list(df3 = data.frame(norm = rnorm(4))))

The result I expect after binding this two lists by names is:

> list3
$list_a
$list_a$df1
  letters numbers
1       A       1
2       B       2
3       C       3
4       D       4
5       E       5
6       F       6

$list_a$df2
   letters numbers
1        A       1
2        B       2
3        C       3
4        D       4
5        E       5
6        F       6
7        G       7
8        H       8
9        I       9
10       J      10


$list_b
$list_b$df3
        norm
1  0.1400504
2 -0.5785170
3 -0.2905891
4  1.9175712
5  1.8736454
6 -0.4895259
7  0.5975914
8  0.3586774

So, in brief what I really want to do is bind the respective data frame from this two nested list by its names.

Any ideas?


Solution

  • Assume that list1 and list2 have a mutual structure(identical depth, list names, order), you could use a nested Map():

    Map(\(x, y) Map(rbind, x, y), list1, list2)
    
    $list_a
    $list_a$df1
      letters numbers
    1       A       1
    2       B       2
    3       C       3
    4       D       4
    5       E       5
    6       F       6
    
    $list_a$df2
       letters numbers
    1        A       1
    2        B       2
    3        C       3
    4        D       4
    5        E       5
    6        F       6
    7        G       7
    8        H       8
    9        I       9
    10       J      10
    
    
    $list_b
    $list_b$df3
            norm
    1  0.6370310
    2  0.3425583
    3 -0.8333353
    4  1.5825106
    5 -0.2551183
    6  1.1983533
    7 -1.0771730
    8 -1.1065747