r - Functional way to stack list of 2d matrices into 3d matrix -
after clever lapply
, i'm left list of 2-dimensional matrices.
for example:
set.seed(1) test <- replicate( 5, matrix(runif(25),ncol=5), simplify=false ) > test [[1]] [,1] [,2] [,3] [,4] [,5] [1,] 0.8357088 0.29589546 0.9994045 0.2862853 0.6973738 [2,] 0.2377494 0.14704832 0.0348748 0.7377974 0.6414624 [3,] 0.3539861 0.70399206 0.3383913 0.8340543 0.6439229 [4,] 0.8568854 0.10380669 0.9150638 0.3142708 0.9778534 [5,] 0.8537634 0.03372777 0.6172353 0.4925665 0.4147353 [[2]] [,1] [,2] [,3] [,4] [,5] [1,] 0.1194048 0.9833502 0.9674695 0.6687715 0.1928159 [2,] 0.5260297 0.3883191 0.5150718 0.4189159 0.8967387 [3,] 0.2250734 0.2292448 0.1630703 0.3233450 0.3081196 [4,] 0.4864118 0.6232975 0.6219023 0.8352553 0.3633005 [5,] 0.3702148 0.1365402 0.9859542 0.1438170 0.7839465 [[3]] ...
i'd turn 3-dimensional array:
set.seed(1) replicate( 5, matrix(runif(25),ncol=5) )
obviously, if i'm using replicate can turn on simplify
, sapply
not simplify result properly, , stack
fails utterly. do.call(rbind,mylist)
turns 2d matrix rather 3d array.
i can loop, i'm looking neat , functional way handle it.
the closest way i've come is:
array( do.call( c, test ), dim=c(dim(test[[1]]),length(test)) )
but feel that's inelegant (because disassembles , reassembles array attributes of vectors, , needs lot of testing make safe (e.g. dimensions of each element same).
you can use abind
package , use do.call(abind, c(test, along = 3))
library(abind) testarray <- do.call(abind, c(test, along = 3))
or use simplify = 'array'
in call sapply
, (instead of lapply
). simplify = 'array'
not same simplify = true
, change argument higher
in simplify2array
eg
foo <- function(x) matrix(1:10, ncol = 5) # default simplify = true sapply(1:5, foo) [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 2 2 2 2 2 [3,] 3 3 3 3 3 [4,] 4 4 4 4 4 [5,] 5 5 5 5 5 [6,] 6 6 6 6 6 [7,] 7 7 7 7 7 [8,] 8 8 8 8 8 [9,] 9 9 9 9 9 [10,] 10 10 10 10 10 # *not* want # set `simplify = 'array' sapply(1:5, foo, simplify = 'array') , , 1 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10 , , 2 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10 , , 3 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10 , , 4 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10 , , 5 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10
Comments
Post a Comment