[R] Why are looping variables not local?

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 28 16:43:04 CET 2001


The difference is in the FAQ:

   * In S, the index variable in a `for()' loop is local to the inside of
     the loop.  In R it is local to the environment where the `for()'
     statement is executed.

It is related to the treatment of {...}.  In S that starts a separate
frame: in R it does not (do the equivalent).  So you are probably
interpreting { ... } in a C-like way, and R is not like that.



On Wed, 28 Nov 2001, Richard Nixon wrote:

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

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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