Combining matrices into an array in R Combining matrices into an array in R arrays arrays

Combining matrices into an array in R


You can use the abind function from the abind package:

library(abind)newarray <- abind( mat1, mat2, mat3, mat4, along=3 )## or if mats are in a list (a good idea)newarray <- abind( matlist, along=3 )


here's the example for two. you can easily extend this to eight

# create two matricies with however many rows and columnsx <- matrix( 1:9 , 3 , 3 )y <- matrix( 10:18 , 3 , 3 )# look at your starting dataxy# store both inside an array, with the same first two dimensions,# but now with a third dimension equal to the number of matricies# that you are combiningz <- array( c( x , y ) , dim = c( 3 , 3 , 2 ) )# resultz


The short version is that you can simplify-to-array a set of matrices using the function: simplify2array:

simplify2array(list(x,y))

Below is my previous answer showing how to do this with sapply's simplify= argument, since ‘simplify2array()’ is the utility called from ‘sapply()’ when ‘simplify’ is not false - see the ?sapply help file.

Here's a version similar to abind-ing, but without using any additional packages. Collect everything into a list and then use sapply's option to simplify= to an "array", after doing nothing to each part of the list (identity just returns the object and is equivalent to function(x) x ):

sapply(list(x,y), identity, simplify="array")# similarly to save a couple of keystrokes, the following is usually identicalsapply(list(x,y), I, simplify="array")#, , 1##     [,1] [,2] [,3]#[1,]    1    4    7#[2,]    2    5    8#[3,]    3    6    9##, , 2##     [,1] [,2] [,3]#[1,]   10   13   16#[2,]   11   14   17#[3,]   12   15   18

If you want to retain the names of each original matrix in your new array as identifiers, try:

sapply(mget(c("x","y")), identity, simplify="array")