pat-s
pat-s

Reputation: 6302

R: Flexible passing of sublists to following function

Building upon question Adding a vector to each sublist within a list R.

Reproducible example

Taking a slightly modified example here:

I have a list with multiple sublists which store x vectors (here two):

listA <- list(list(c(1,2,3,2), c(7,3,1,2)),
              list(c(2,1,3,2), c(2,4,5,1)), 
              list(c(1,4,6,8), c(5,2,4,4)))

My desired output is achieved with

Map(list, listA[[1]], listA[[2]], listA[[3]])

In words, I want to combine all 'first', 'second', ..., 'inf' vectors of each sublist in a separate sublist to be able to work with that new ordered list afterwards. This works with the Map() call shown above.

Challenge

The problem I'm facing is that length(listA) is flexible in my case (within a function). So it could be that I have three lists (as in the example) or 100 or 59, etc.
Map() only works as desired if I pass all sublists (here listA[[1]], listA[[2]], listA[[3]) in a single call as shown above.

So how can I interactively check how many sublists listA contains and pass all of these sublists to the Map() call?

Upvotes: 4

Views: 111

Answers (2)

akrun
akrun

Reputation: 887048

We can use do.call

res <- do.call(Map, c(f= list, listA))
resO <- Map(list, listA[[1]], listA[[2]], listA[[3]])
identical(res, resO)
#[1] TRUE

Or as @alexis_laz commented with .mapply

.mapply(list, listA, NULL)

Or another option is transpose from purrr

library(purrr)
transpose(listA)

Upvotes: 4

KenHBS
KenHBS

Reputation: 7164

Another option would be this:

newlist <- list()
for(i in 1:length(listA[[1]])){
   newlist[[i]] <- sapply(listA, "[", i)
}

Upvotes: 0

Related Questions