[R] storing matrix(variables) in loop

William Dunlap wdunlap at tibco.com
Mon Mar 15 16:36:23 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Márcio Resende
> Sent: Monday, March 15, 2010 7:45 AM
> To: r-help at r-project.org
> Subject: [R] storing matrix(variables) in loop
> 
> 
> Hello R-helpers,
> I have the following code that works well, 
> 
> b <-list()
> for (i in 1:3){
> a <- matrix(runif(1),3,3)
> b[[i]] <- a
> }
> b
> 
> however, I need to do something similar with two loops and I 
> was looking for
> something that would look like
> 
> b <- list()
> for (i in 1:3){
> for (j in 1:4){
> a <- matrix(runif(1),3,3)
> b[[i,j]] <- a #but this doesn´t work
> }
> }

To use multidimensional subscripting on
b you must tell the system what the dimensions
of b are.  E.g., make b with
   b <- matrix(list(), nrow=3, ncol=4) 
(instead of b<-list()) and then run your
nested loops.

After the loops b will be a 3x4 matrix, each of
whose elements contains a 3x3 matrix.  Is that
what you wanted?  If all the elements are of the
same size and type, a 3x3x3x4 numeric "array" may be
more convenient.

Another approach is to make b a list of 3 lists,
each of which is a list of 4 3x3 matrices:
 b <- list()
 for(i in 1:3) {
    b[[i]] <- list()
    for(j in 1:4) {
      b[[i]][[j]] <- matrix(10*i+j+runif(1), 3, 3)
    }
 }
after which we get
 > b[[2]][[4]]
          [,1]     [,2]     [,3]
 [1,] 24.42999 24.42999 24.42999
 [2,] 24.42999 24.42999 24.42999
 [3,] 24.42999 24.42999 24.42999
or the equivalent
 > b[[c(2,4)]]
          [,1]     [,2]     [,3]
 [1,] 24.42999 24.42999 24.42999
 [2,] 24.42999 24.42999 24.42999
 [3,] 24.42999 24.42999 24.42999

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> 
> Anyway, I wanted "b" to loop like
> [[i=1, j=1]]         [[i=1, j=2]]     (...)
> a[i=1, j=1]           a[i=1,j=2]      (...)
> 
> [[i = 2, j=1]]    (...)
> a[i = 2, j = 1]   (...)
> 
> (...)
> 
> Can anybody help me?
> Thanks
> 
> -- 
> View this message in context: 
> http://n4.nabble.com/storing-matrix-variables-in-loop-tp159346
1p1593461.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list