0

List "l_start" at level 1 is a named list, itself nesting named lists ("l1", "l1a") at level 2, in turn containing 2-3 data.frames (a, b and possibly c) at level 3.

Goal is to rbind the data frames at level 3 based on names if available to get "l_finish" (A data.table & rlist solution be preferred, but purrr or base would be fine also)

# Level 2
l1 <- 
  # Level 3
  list(a = data.frame(matrix(1:4, ncol=2)),
       b = data.frame(matrix(1:4, ncol=2)),
       c= data.frame(matrix(1:4, ncol=2)))

# Level 2
l1a <- 
  # Level 3
  list(a = data.frame(matrix(1:6, ncol=2)),
       b = data.frame(matrix(1:6, ncol=2)))


# Level 1 "l_start"
l_start <- 
  list(l1, l1a)
names(l_start) <- c("l1", "l1a")

How "l_finish" should look

l_finish <- 
  list(l1_1a = list(a = rbind(l1$a, l1a$a),
                 b = rbind(l1$b, l1a$b)))

Hoped for final product "l_finish" Note that c is dropped because not in both lists

l_finish
#> $l1_1a
#> $l1_1a$a
#>   X1 X2
#> 1  1  3
#> 2  2  4
#> 3  1  4
#> 4  2  5
#> 5  3  6
#> 
#> $l1_1a$b
#>   X1 X2
#> 1  1  3
#> 2  2  4
#> 3  1  4
#> 4  2  5
#> 5  3  6

Close but couldn't quite get there with these

Rbind happening one level above my example rbind dataframes across nested lists

Only one df name in the list, not multiple rbind data.frames in a list in R

David Lucey
  • 252
  • 3
  • 9

1 Answers1

1

A purrr solution :

library(purrr)
cols <- intersect(names(l_start[[1]]), names(l_start[[2]]))

map(l_start, `[`, cols) %>% transpose() %>% map(bind_rows)

#$a
#  X1 X2
#1  1  3
#2  2  4
#3  1  4
#4  2  5
#5  3  6

#$b
#  X1 X2
#1  1  3
#2  2  4
#3  1  4
#4  2  5
#5  3  6

We select the common names in list using intersect, transpose them and bind the rows.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you so much, this indeed answers my original question. I made a mistake though, I have multiple lists at level 2, each including varying data.frames. list(l1, l1a, l2, l2a) to transform to list(l1_1a, l2_l2a). Are you able to modify your answer to allow for this multiple level 2 lists? Apologies for not getting it right on the first try. – David Lucey Mar 21 '20 at 16:33
  • @DavidLucey hmmm...I am not sure if I understand. Can you post an example of your actual list structure and show the expected output for the same? – Ronak Shah Mar 22 '20 at 00:45
  • I found another way to do it, but yours answered the question I asked, so accepted. Many thanks – David Lucey Mar 22 '20 at 21:51