user3032689
user3032689

Reputation: 667

Transpose a nested list

I would like to transpose a nested list. Assume the following nested list x is given:

a <- list(c("a","b","c","d"))
b <- list(c("d","c","b","a"))
c <- list(c("4","3","2","1"))
d <- list(c("1","2","3","4"))

x <- list(a,b,c,d)

The outcome should be a nested list where the first column of the original list x is the first nested list element, that is "a","d","4","1", the second column is the second nested list element, i.e. "b","c","3","2" and so on. In the end the structure is kind of a transpose of the original structure. How can this be done in R?

Upvotes: 1

Views: 590

Answers (2)

989
989

Reputation: 12937

We could also do without lapply (using matrix):

relist(matrix(unlist(x), ncol = 4, byrow = T), skeleton = x)

Benchmarking

library(microbenchmark)
a <- list(c("a","b","c","d"))
b <- list(c("d","c","b","a"))
c <- list(c("4","3","2","1"))
d <- list(c("1","2","3","4"))
x <- list(a,b,c,d)

f_akrun <- function(x) {m1 <- do.call(rbind, lapply(x, function(y) do.call(rbind, y)));relist(m1, skeleton = x);}
f_m0h3n <- function(x) {relist(matrix(unlist(x), ncol = length(x[[1]][[1]]), byrow = T), skeleton = x)}

setequal(f_akrun(x), f_m0h3n(x))
# [1] TRUE
microbenchmark(f_akrun(x), f_m0h3n(x))

# Unit: microseconds
   # expr     min      lq     mean  median      uq     max neval
 # f_akrun(x) 135.591 137.301 144.3545 138.585 148.422 334.484   100
 # f_m0h3n(x) 110.782 111.638 116.5477 112.493 117.412 212.153   100

Upvotes: 4

akrun
akrun

Reputation: 887008

We can try

m1 <- do.call(rbind, lapply(x, function(y) do.call(rbind, y)))
relist(m1, skeleton = x)

Upvotes: 3

Related Questions