Skip to content
Prev 168585 / 398502 Next

scoping rules for 'for' [was - Re: for/if loop ]

I apologize for posting a wrong opinion; I should of course have checked
before posting.

Henrik's examples illustrate something I had never realized before, and
it really surprised me!
Where can I read the technical details of this scoping aspect of 'for'
as it still presents
some subtle puzzles for me. For example:
<- ii + 1); print(ii)}
[1] 1
[1] 20
[1] 21
[1] 21
[1] 2
[1] 2
[1] 3
[1] 3
[1] 3
[1] 3
[1] 4
[1] 4
Why does R treat ii differently after the 'if' in the first and
subsequent iterations?
And if the loop variable does not exist before the 'for', why is it
created in the parent(?) environment at all?
(I.e, if ii did not exist before the for loop, it does and has value 5
after. Wouldn't strict
scoping mean that ii exists only within the for loop?)

I generally don't try to change the loop variable's value inside a loop,
but coming from C
or other languages, it seems natural to do so in certain circumstances.
And the examples are
certainly bad programming style. But I remain confused. I assume that
'while' loops have different scoping
rules?

Thanks,

-- David


-----Original Message-----
From: henrik.bengtsson at gmail.com [mailto:henrik.bengtsson at gmail.com] On
Behalf Of Henrik Bengtsson
Sent: Wednesday, January 28, 2009 5:08 PM
To: David Reiner <davidr at rhotrading.com>
Cc: SnowManPaddington; r-help at r-project.org
Subject: Re: [R] - Re: for/if loop
On Wed, Jan 28, 2009 at 2:41 PM, <davidr at rhotrading.com> wrote:
comparing
That is actually not the case (because of the scoping rules for for(),
I think).  Example:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Another "counter intuitive" (though it isn't) example:

for (ii in 1:3) {
  cat("Outer ii:",ii,"\n");
  for (ii in ii:3) {
    cat("  Inner ii:",ii,"\n");
  }
}

Outer ii: 1
  Inner ii: 1
  Inner ii: 2
  Inner ii: 3
Outer ii: 2
  Inner ii: 2
  Inner ii: 3
Outer ii: 3
  Inner ii: 3

My $.02

/Henrik
what
[mailto:r-help-bounces at r-project.org]
the
to
I
or