0

Suppose we have two lists:

l1 <- list("a", "b", "c")
l2 <- list("d", "e", "f")

How can we combine them into a single list to obtain this output?

[[1]]
[1] "a"

[[2]]
[1] "d"

[[3]]
[1] "b"

[[4]]
[1] "e"

[[5]]
[1] "c"

[[6]]
[1] "f"

In practice, I need a general solution that scales to lists of any size, and lists with any object (e.g., dataframe, other lists, etc). In other words, pretend that the letters in the list above are actually data.frames

Rich Pauloo
  • 7,734
  • 4
  • 37
  • 69

1 Answers1

1

You can do :

as.list(c(rbind(l1, l2)))

#[[1]]
#[1] "a"

#[[2]]
#[1] "d"

#[[3]]
#[1] "b"

#[[4]]
#[1] "e"

#[[5]]
#[1] "c"

#[[6]]
#[1] "f"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Brilliant. Thanks! This is the solution I was looking for. The trick here is recognizing that you can rbind two vectors into a matrix, and when you concatenate a matrix, it's combined along columns from left to right, giving that offset. In fact, if the objects in the list are not strings, but dataframes, the solution can be more general `c(rbind(l1, l2))`, and you don't need `as.list()`. – Rich Pauloo Jan 22 '21 at 10:12