# [R] for loop question

Ben Bolker ben at zoo.ufl.edu
Tue Sep 11 21:45:10 CEST 2001

```  This is a "gotcha", which I think I will add to my list of "R traps"
(http://www.zoo.ufl.edu/bolker/emd/R/R-traps.html).

The problem is in "operator precedence", or "priority": the colon
operator has higher precedence than the plus operator, so R treats

i+1:3

as

i+(1:3)

rather than

(i+1):3

(which is what you should write to get the behavior you expected).  I'm
not sure where this is found in the documentation.

OK, p. 14 of the "Introduction to R" says

The colon operator has highest priority within an expression, so, for
example 2*1:15 is the vector c(2, 4, ..., 28, 30). Put n <- 10 and
compare the sequences 1:n-1 and 1:(n-1).

On Tue, 11 Sep 2001, HEUMANN,JOHN (A-Loveland,ex1) wrote:

> In the windows version of R (1.3.0) is the following a bug, a
> known problem, or expected behavior:
>
>  > for (i in 1:2) {
>  + for (j in i+1:3) {
>  + print(j)
>  + }
>  + }
>  [1] 2
>  [1] 3
>  [1] 4      ????
>  [1] 3
>  [1] 4      ????
>  [1] 5      ????
>  >
>
> Conversely, the following behaves as expected:
>
>  > for (i in 1:2) {
>  + k <- i+1
>  + for (j in k:3) {
>  + print(j)
>  + }
>  + }
>  [1] 2
>  [1] 3
>  [1] 3
>  >
>
> This is under NT4, SP5 using a pre-compiled binary from CRAN.
>
> Thanks,
> -jh-
>
> =========================================
> John M. Heumann, Agilent Technologies
> 815 14th St. S.W., Loveland, CO 80537 USA
> Email: john_heumann at agilent.com
> Phone: 970 679-3761 FAX: 970 679-5399
> =========================================
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>

--
318 Carr Hall                                bolker at zoo.ufl.edu
Zoology Department, University of Florida    http://www.zoo.ufl.edu/bolker
Box 118525                                   (ph)  352-392-5697
Gainesville, FL 32611-8525                   (fax) 352-392-3704

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

```