Skip to content

calling objects in a foreloop

2 messages · Benjamin M. Osborne, Thomas Lumley

#
I want to organize outputs from several regressions into a handy table.  When I
try the following, each of my "fit_s" is replaces instead of read.  Is there a
way to read from the regression summaries that does not require writing
separate lines of code for each?
-Ben Osborne
+ dBA.spp16.fits[i,1]<-summary(as.name(paste("fit",i,sep="")))$call
+ dBA.spp16.fits[i,2]<-summary(as.name(paste("fit",i,sep="")))$coef[1,1]
+ dBA.spp16.fits[i,3]<-summary(as.name(paste("fit",i,sep="")))$coef[2,1]
+ dBA.spp16.fits[i,4]<-summary(as.name(paste("fit",i,sep="")))$r.squared
+ dBA.spp16.fits[i,5]<-summary(as.name(paste("fit",i,sep="")))$adj.r.squared
+ }
Error in "[<-"(`*tmp*`, i, 1, value = NULL) :
        number of items to replace is not a multiple of replacement length

# Because:
Length  Class   Mode
     1   name   name
#
On Mon, 14 Mar 2005, Benjamin M. Osborne wrote:

            
Put the lm objects into a list rather than into separate variables, then 
you can loop or lapply() over the list.

fits<-vector("list",8)
fits[[1]]<-lm(dBA.spp16$sp2.dBA.ha~dBA.spp16$sp1.dBA.ha)
fits[[2]]<-lm(dBA.spp16$sp3.dBA.ha~dBA.spp16$sp1.dBA.ha)
etc

dBA.spp16.fits<-matrix(NA, nrow=8, ncol=5)
for (i in 1:8){
     summ<-summary(fit[[i]])
     dBA.spp16.fits[i,2]<-summ$coef[1,1]
     dBA.spp16.fits[i,3]<-summ$coef[2,1]
     dBA.spp16.fits[i,4]<-summ$r.squared
     dBA.spp16.fits[i,5]<-summ$adj.r.squared
}

Other things to note

1/  You can't put the formula into a numeric matrix
2/ lm(dBA.spp16$sp2.dBA.ha~dBA.spp16$sp1.dBA.ha) can be more elegantly 
written as
    lm(sp2.dBA.ha~sp1.DB.ha, data=dBA.spp16)


When you find yourself doing computations on the names of objects rather 
than on their values it is usually a bad sign.


 	-thomas