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

Don MacQueen macq at llnl.gov
Mon Aug 26 21:31:38 CEST 2002


Try 'while' instead of 'for'.
See ?Control.

Here's an example
>  n <- 3
>  while (n < 10) { cat(n,'before\n')
+        n <- 6; cat(n,'during\n') ; n <- 13 ; cat(n,'after\n') }
3 before
6 during
13 after

-Don

At 10:54 AM -0700 8/26/02, Prasad, Rajiv wrote:
>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 
>status                 
>major    1             
>minor    5.1           
>year     2002          
>month    06            
>day      17            
>language R             
>
>
>Rajiv
>--------
>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
>_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
--------------------------------------
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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