3

I have a vector and would like to extract element 3 and 4. Can you please help me understand what the logic is behind the code version without parenthesis? I appreciate your help.

a=c(1:5)
a[(2+1): 4]    # with parenthesis, makes sense
[1] 3 4
a[ 2+1 : 4]    # without parenthesis,  what is the logic here?
[1]  3  4  5 NA
denis
  • 5,580
  • 1
  • 13
  • 40
Maxim
  • 39
  • 1

1 Answers1

2

The : operator is evaluated before the + operator. Consider

print(c(2+1:4))

This returns

[1] 3 4 5 6

Because a vector 1,2,3,4 is created, then all elements are added by 2.

R Operator Syntax and Precedence gives an overview over the priority of R's operators. The sequence operator : comes before the arithmetic operators like + or -.

PhillipD
  • 1,797
  • 1
  • 13
  • 23