David Lucey
David Lucey

Reputation: 234

How to rbind data.frames across third level of named lists?

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

Upvotes: 0

Views: 161

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

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.

Upvotes: 1

Related Questions