Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining matrices into an array in R

Tags:

arrays

r

matrix

If I have several matrices that I have created, how can I combine them into one array? I have 8 matrices that each have 200 rows and 200 columns and I need to combine them into an array with dim = 200,200,8. So I want each of my matrices to be a slice of my array.

like image 445
user2113499 Avatar asked Mar 05 '13 00:03

user2113499


People also ask

How do I combine matrices in R?

Combining two matrices in R To combine two or more matrices in R, we use the following functions: rbind() : Used to add the matrices as rows. cbind() : Used to add the matrices as columns.

How do I turn an array into a matrix in R?

To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c).

How do you add to an array in R?

Creating an Array An array in R can be created with the use of array() function. List of elements is passed to the array() functions along with the dimensions as required. dimnames : Default value = NULL. Otherwise, a list has to be specified which has a name for each component of the dimension.

How do you combine two matrices?

Concatenating Matrices You can also use square brackets to join existing matrices together. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector. To arrange A and B as two rows of a matrix, use the semicolon.


2 Answers

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 ) 
like image 177
Greg Snow Avatar answered Oct 08 '22 22:10

Greg Snow


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

# create two matricies with however many rows and columns x <- matrix( 1:9 , 3 , 3 ) y <- matrix( 10:18 , 3 , 3 ) # look at your starting data x y  # 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 combining z <- array( c( x , y ) , dim = c( 3 , 3 , 2 ) )  # result z 
like image 36
Anthony Damico Avatar answered Oct 08 '22 22:10

Anthony Damico