0

I have a list containing multiple lists which all have the same structure:

ls <- list(
one = list(df = data.frame(var1_1 = c(1, 1, 1),
                           var1_2 = c('a', 'a', 'a')),
           ls = list(n_df_1 = data.frame(var3_1 = c('x', 'x', 'x'),
                                         var3_2 = c(4, 4, 4))),
           name = c("one", "one", "one")),
two = list(df = data.frame(var1_1 = c(1, 1, 1),
                           var1_2 = c('a', 'a', 'a')),
           ls = list(n_df_1 = data.frame(var3_1 = c('x', 'x', 'x'),
                                         var3_2 = c(4, 4, 4))),
           name = c("two", "two", "two")))

I want to merge all these nested lists like stated here: Merge Two Lists in R

It does exactly what want if I do this:

merged <- mapply(c, ls[[1]], ls[[2]], SIMPLIFY = FALSE)

The problem is, is that the main list (ls) doesn't always have only two nested lists. How can I make this code more modular?

I tried to make a vector containing all indexes of the nested lists:

sapply(seq_along(ls), function(x) paste0("ls[[", x, "]]"))

Which output this:

[1] "ls[[1]]" "ls[[2]]"

I thought I could unquote these character vector so that R sees them as object. But I can't figure out how to do that (if it's even possible). I looked at tidy eval for this, but I'm don't know if this is the way to do it.

Any suggestions?

Artie16
  • 59
  • 4
  • 2
    Please don't name your list `ls`. There is a predefine function `ls` in R which you overwrite by redefining it – Sotos Aug 07 '19 at 12:09

1 Answers1

4

You can use Reduce to do it on an abstract number of list elements, i.e.

Reduce(function(...)Map(c, ...), l1) #Map = mapply(..., simplify = FALSE)

which gives,

$df
$df$var1_1
[1] 1 1 1

$df$var1_2
[1] a a a
Levels: a

$df$var1_1
[1] 1 1 1

$df$var1_2
[1] a a a
Levels: a


$ls
$ls$n_df_1
  var3_1 var3_2
1      x      4
2      x      4
3      x      4

$ls$n_df_1
  var3_1 var3_2
1      x      4
2      x      4
3      x      4


$name
[1] "one" "one" "one" "two" "two" "two"

DATA:

dput(l1)
list(one = list(df = structure(list(var1_1 = c(1, 1, 1), var1_2 = structure(c(1L, 
1L, 1L), .Label = "a", class = "factor")), class = "data.frame", row.names = c(NA, 
-3L)), ls = list(n_df_1 = structure(list(var3_1 = structure(c(1L, 
1L, 1L), .Label = "x", class = "factor"), var3_2 = c(4, 4, 4)), class = "data.frame", row.names = c(NA, 
-3L))), name = c("one", "one", "one")), two = list(df = structure(list(
    var1_1 = c(1, 1, 1), var1_2 = structure(c(1L, 1L, 1L), .Label = "a", class = "factor")), class = "data.frame", row.names = c(NA, 
-3L)), ls = list(n_df_1 = structure(list(var3_1 = structure(c(1L, 
1L, 1L), .Label = "x", class = "factor"), var3_2 = c(4, 4, 4)), class = "data.frame", row.names = c(NA, 
-3L))), name = c("two", "two", "two")))
Sotos
  • 51,121
  • 6
  • 32
  • 66