[R] updating n within for(i in 1:n) loop

Prasad, Rajiv Rajiv.Prasad at pnl.gov
Mon Aug 26 19:54:48 CEST 2002

Hi folks:

I think I'm having problems with figuring this one out:

test1 <- function()
  n <- 2

  for(i in 1:n)
    cat(paste("i =", i, "\n")); flush.console()
    n <- 5  # version 1
    #n <<- 5  # version 2
    #assign("n", 5, envir = environment(test1))  # version 3

I need the for(.) loop to run (say) n=5 times within the function, but I do
not know that before the loop begins.  In other words, n is to be updated
during computations within the for(.) loop.  This code prints "i = 1" and "i
= 2" only.  If I modify test1(.) to use version 2 or version 3 of the
assignment, there is no change to the output, and I end up with an "n" in
the parent environment with value 5.  So the problem is to assign 5 to n in
the calling environment of the for(.) loop??  (I'm sure my terminology is
quite mixed up here -- please feel free to comment.)

How do I do this?

Thanks in advance.

> version
platform i386-pc-mingw32
arch     i386           
os       mingw32        
system   i386, mingw32  
major    1              
minor    5.1            
year     2002           
month    06             
day      17             
language R              

Rajiv Prasad
Postdoctoral Research Associate, Hydrology Group
Pacific Northwest National Laboratory, P.O. Box 999, MSIN K9-33
Richland, WA 99352
Voice: (509) 375-2096  Fax: (509) 372-6089  Email: rajiv.prasad at pnl.gov

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list