[R] "for" loop in R - strange behaviour

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jan 29 20:20:52 CET 2014


On 29/01/2014 11:32 AM, Supriya Jain wrote:
> Hi, I notice the following from a "for" loop in R, which seems strange to
> me:
>
> When I  do this:
>
> -------
> first <- 0
> nstep <- 10
> N <- 14
> while(first < N)
> {
>   print("-------> ")
>   last <- first + nstep
>   if(last > N)
>      last <- N
>   #start <- first+2
>   for(i in (first+2):last)                            #  line 11
>      print(sprintf("i: %d; last: %d", i, last))
>   first <- first + nstep
> } # end of while loop
> -------
>
> the output is as expected:
>
> [1] "-------> "
> [1] "i: 2; last: 10"
> [1] "i: 3; last: 10"
> [1] "i: 4; last: 10"
> [1] "i: 5; last: 10"
> [1] "i: 6; last: 10"
> [1] "i: 7; last: 10"
> [1] "i: 8; last: 10"
> [1] "i: 9; last: 10"
> [1] "i: 10; last: 10"
> [1] "-------> "
> [1] "i: 12; last: 14"
> [1] "i: 13; last: 14"
> [1] "i: 14; last: 14"
>
> but, if, on line 11 in code, I forget to enclose first+2 in parenthesis,
> that is, do:
>                  for(i in first+2:last)
> the output from the second iteration is very non-intuitive:
>
> [1] "-------> "
> [1] "i: 2; last: 10"
> [1] "i: 3; last: 10"
> [1] "i: 4; last: 10"
> [1] "i: 5; last: 10"
> [1] "i: 6; last: 10"
> [1] "i: 7; last: 10"
> [1] "i: 8; last: 10"
> [1] "i: 9; last: 10"
> [1] "i: 10; last: 10"
> [1] "-------> "
> [1] "i: 12; last: 14"
> [1] "i: 13; last: 14"
> [1] "i: 14; last: 14"
> [1] "i: 15; last: 14"
> [1] "i: 16; last: 14"
> [1] "i: 17; last: 14"
> [1] "i: 18; last: 14"
> [1] "i: 19; last: 14"
> [1] "i: 20; last: 14"
> [1] "i: 21; last: 14"
> [1] "i: 22; last: 14"
> [1] "i: 23; last: 14"
> [1] "i: 24; last: 14"
>
> Here, even though the "last" is 14, "i" does not stop at 14, but goes on
> till first (= 10)+14 = 24.
>
> --
> Any insights on why this is happening?

Operator precedence.  first + 2:last is the same as

first + (2:last)

When first is 10 and last is 14, this is a sequence from 12 to 24.

Duncan Murdoch




More information about the R-help mailing list