R Language Range and addition


Example

Let's take an example of adding a value to a range (as it could be done in a loop for example):

3+1:5

Gives:

[1] 4 5 6 7 8

This is because the range operator : has higher precedence than addition operator +.

What happens during evaluation is as follows:

  • 3+1:5
  • 3+c(1, 2, 3, 4, 5) expansion of the range operator to make a vector of integers.
  • c(4, 5, 6, 7, 8) Addition of 3 to each member of the vector.

To avoid this behavior you have to tell the R interpreter how you want it to order the operations with ( ) like this:

  (3+1):5

Now R will compute what is inside the parentheses before expanding the range and gives:

 [1] 4 5