[R] Looping with incremented object name and increment function

Greg Snow Greg.Snow at imail.org
Fri Jan 21 22:43:31 CET 2011


This is FAQ 7.21.

The real gem in the answer there is at the end where it tells you that it is easier to just use a list.  If your fit1, fit2, fit3, and fit4 were elements in a list then you can just loop through the list elements, or even easier use the lapply function to loop through the list elements for you.

The syntax fit[ii] means that you want the ii'th element of the vector named "fit", the FAQ shows how to do what you want, but in the long run (and the medium run, and even the short run) using a list instead of separate global variables will make your life easier.

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Michael Costello
> Sent: Friday, January 21, 2011 9:43 AM
> To: r-help at r-project.org
> Subject: [R] Looping with incremented object name and increment
> function
> 
> Folks,
> 
> I am trying to get a loop to run which increments the object name as
> part of
> the loop.  Here "fit1" "fit2" "fit3" and "fit4" are linear regression
> models
> that I have created.
> 
> > for (ii in c(1:4)){
> + SSE[ii]=rbind(anova(fit[ii])$"Sum Sq")
> + dfe[ii]=rbind(summary(fit[ii])$df)
> + }
> Error in anova(fit[ii]) : object 'fit' not found
> 
> Why isn't it looking for object 'fit1' instead of 'fit'?
> 
> The idea is that it would store in SSE1 the Sum Sq of the model fit1,
> and so
> on for the other 3 models.  Is there a way to do this in R?  I can do
> it in
> Stata, but am only somewhat knowledgeable in R.
> 
> -Michael
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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