Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R creating an array of matrices

I would like to create an array of matrices in such a way that I first create an array of k matrices with NA values and then loop over k and update each k'th matrix through the array.

Any suggestions?

like image 918
user1701545 Avatar asked Feb 20 '13 20:02

user1701545


2 Answers

I'm probably missing the point, but won't:

k = 2; n=3; m = 4
array(NA, c(n,m,k))

, , 1

     [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA

, , 2

     [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA

give you what you want? Then you can loop as normal:

R> for(k in 1:2){print(a[,,k])}
like image 124
csgillespie Avatar answered Sep 28 '22 05:09

csgillespie


Beware of terminology :-) . As CSGillespie points out, you can define an N-rank array in R . Alternatively, you could create a list variable, each entry of which contains a matrix. The advantage to the latter is that the matrices can be of differing sizes. The disadvantage is that it can be rather more painful to create the inital state.

E.g.

mat1 <- matrix(NA, 3,5)
mat2 <- matrix(NA, 4,7)
matlist <- list(mat1=mat1,mat2=mat2)
like image 29
Carl Witthoft Avatar answered Sep 28 '22 03:09

Carl Witthoft