R Language Arithmetic Operators Range and addition

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any R Language Question?