Theodor
Theodor

Reputation: 1026

concatenate vectors from a lists of lists

I would like to have a general solution to a certain problem. I have a nested list; each element of this list is a list with named elements. For example:

mylist <- list(
  list(x1 = 1:10, x2 = letters[1:5]),
  list(x1 = 11:14, x2 = letters[6:15])
)

here mylist[[1]] and mylist[[2]] each have vectors x1 and x2.

I would like to concatenate all the x1 vectors and x2 vectors, such as to obtain:

c(mylist[[1]]$x1, mylist[[2]]$x1)
c(mylist[[1]]$x2, mylist[[2]]$x2)

but for a general case where mylist might have n elements.

If I knew a priori that mylist has only two elements, then I could use

do.call(function(a,b) c(a$x1, b$x1), mylist)
do.call(function(a,b) c(a$x2, b$x2), mylist)

but I do not know how to generalize this for n elements.

Upvotes: 0

Views: 1143

Answers (2)

Nick F
Nick F

Reputation: 311

If you want to do this using the tidyverse then:

library(tidyverse)

Edit based on comment from @jbaums and noting that flatten returns a list not a vector:

purrr::transpose(mylist) %>% purrr::map(unlist)

Upvotes: 0

Ryan
Ryan

Reputation: 934

vecs <- unlist(mylist, recursive = F)
lapply(unique(names(vecs)), function(name) do.call(c, vecs[name == names(vecs)]))

Upvotes: 2

Related Questions