r - Transpose a List of Lists -


i have list contains list entries, , need transpose structure. original structure rectangular, names in sub-lists not match.

here example:

ax <- data.frame(a=1,x=2) ay <- data.frame(a=3,y=4) bw <- data.frame(b=5,w=6) bz <- data.frame(b=7,z=8) before <- list(  a=list(x=ax, y=ay),   b=list(w=bw, z=bz)) 

what want:

after  <- list(w.x=list(a=ax, b=bw), y.z=list(a=ay, b=bz)) 

i not care names of resultant list (at level).

clearly can done explicitly:

after <- list(x.w=list(a=before$a$x, b=before$b$w), y.z=list(a=before$a$y, b=before$b$z)) 

but ugly , works 2x2 structure. what's idiomatic way of doing this?

the following piece of code create list i-th element of every list in before:

lapply(before, "[[", i) 

now have do

n <- length(before[[1]]) # assuming lists in before have same length lapply(1:n, function(i) lapply(before, "[[", i)) 

and should give want. it's not efficient (travels every list many times), , can make more efficient keeping pointers current list elements, please decide whether enough you.


Comments