[R] Matrix of Matrices?

Petr Savicky savicky at praha1.ff.cuni.cz
Fri Feb 11 13:22:47 CET 2011


On Thu, Feb 10, 2011 at 11:54:50PM -0800, Alaios wrote:
> Dear all I have a few matrices that I would like to store alltogether under a bigger object.
> My matrixes with the same name were calculated inside a loop like
> 
> for (few times){
> 
>    estimatedsr<- this is my matrix
>    savematrixasimagefile();
>    
> 
> }
> 
> which means that I was losing all that instances.
> What can I do to keep all these matrices? ( I do not know in advance their number, so I can not preallocate space). 
> How can I store them and adress them back again?
> 
> I would like to thank you in advance in your help

Hello.

A possible approach is to use list (see ?list).

  lst <- list()
  lst[[1]] <- rbind(c(1, 2), c(1, 2))
  lst[[2]] <- rbind(c(3, 3), c(4, 4))
  lst

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

If you know in advance an upper bound on the number of matrices,
then it is possible to use an array (see ?array). For example
storing two matrices 2 x 2 may be done as follows

  a <- array(dim=c(2, 2, 2))
  a[,,1] <- rbind(c(1, 2), c(1, 2))
  a[,,2] <- rbind(c(3, 3), c(4, 4))
  a

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

Hope this helps.

Petr Savicky.



More information about the R-help mailing list