[R] Why are looping variables not local?

Richard Nixon richard.nixon at mrc-bsu.cam.ac.uk
Wed Nov 28 15:55:03 CET 2001


Hello,
I've had a quick look on the list and can't find an answer to this niggle.

Whilst debugging some code, I noticed that looping variables in R are not 
local to the loop as seams common in procedural  languages.
For example consider the following piece of code: 

for(i in 1:3){
   cat(i,"")
   for(i in c("a","b","c")){
      cat(i,"")
   }
      cat(i,"\n")
}

In splus this will produce
1 a b c 1 
2 a b c 2 
3 a b c 3 

but in R it produces
1 a b c c 
2 a b c c 
3 a b c c 

That is the second "cat(i,"\n")" in the outer loop has taken the last value of 
i in the inner loop.

Is anyone in the know as to why R uses global variables in loops? Just curious 
really, now I know how it works I can watch for it!

Thanks
Richard

-- 
Dr. Richard Nixon
MRC Biostatistics Unit, Institute of Public Health,
Robinson Way, Cambridge, CB2 2SR

Alternative email: rmn20 at cam.ac.uk
http://www.mrc-bsu.cam.ac.uk/personal/richard
Tel: +44 (0)1223 330382, Fax: +44 (0)1223 330388

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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