[R] saving estimates from a for loop for later use

Liaw, Andy andy_liaw at merck.com
Sat Apr 8 04:10:01 CEST 2006


If the matrices you're storing inside the loop are all the same dimension
(as in your example), it's probably better to store them in an array; e.g.:

i1 <- 2:3
i2 <- 11:12
x <- array(0, c(4, 1, length(i1), length(i2)))

for (i in seq(along=i1)) {
    for (j in seq(along=i2)) {
        x[, , i, j] <- matrix(c(i1[i], i2[j], i1[i] + i2[j], i1[i]*i2[j]),
nrow=4)
    }
}
dimnames(x) <- list(NULL, NULL, i1, i2)
x[, , "2", "11", drop=FALSE]
x[, , "3", "11", drop=FALSE]

(Notice you need the drop=FALSE to keep it a matrix, because it only has one
column.)

Andy

From: Brian Quinif
> 
> I kind of understand this recommendation, but I can't figure 
> out how to work with x once I have created it.  Here is some 
> fully reproducible code.  It creates a 4x1 matrices within 
> the loops.  Once done with the looping, I want to cbind these 
> matrices together.  I know it's a simple question, but I 
> can't figure it out.
> 
> x <- list()
> for (i in 2:3)
> for (j in 11:12) {
> estimates <- matrix(c(i,j,i+j,i*j),nrow=4) 
> x[[as.character(i)]][[as.character(j)]]  <- estimates }
> 
> 
> So, once I've done this, how can I reference, say, the 
> "estimates" matrix created when i=2 and j=12?
> 
> Thanks,
> 
> BQ
> 
> 2006/4/7, jim holtman <jholtman at gmail.com>:
> >
> > use a 'list';
> >
> > x <- list()
> > for (i in 1:3)
> >   for (j in 0:2) {
> >      .....your calculations.....
> >      x[[as.character(i)]][[as.character(j)]] <- yourResults
> > }
> >
> >
> >
> > On 4/7/06, Brian Quinif <bquinif at gmail.com> wrote:
> > >
> > Thanks to the help of many on this list, I am now an R user 
> and have 
> > been able to write some functioning code to do matching estimation.
> >
> > I have two for loops (i in 1:3, and j in 0:2).  Within the loops, I 
> > had been creating matrices of relevant estimation 
> coefficents in order 
> > to make lots of LaTeX tables.
> >
> > Well, now I want to be able to combine the results of many 
> different 
> > estimations from within the loops into one larger table outside the 
> > loops.
> >
> > How can I save the estimation results from each iteration of the 
> > estimation within a loop for later use outside the loop?
> >
> > Thanks,
> >
> > BQ
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list 
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide! 
> > http://www.R-project.org/posting-guide.html
> >
> >
> >
> >
> > --
> > Jim Holtman
> > Cincinnati, OH
> > +1 513 646 9390 (Cell)
> > +1 513 247 0281 (Home)
> >
> > What the problem you are trying to solve?
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list