12

I am trying to extract values from a vector using numeric vectors expressed in two seemingly equivalent ways:

x <- c(1,2,3)
x[2:3]
# [1] 2 3
x[1+1:3]
# [1]  2  3 NA

I am confused why the expression x[2:3] produces a result different from x[1+1:3] -- the second includes an NA value at the end. What am I missing?

Henrik
  • 65,555
  • 14
  • 143
  • 159
Marc
  • 767
  • 6
  • 18
  • 1+1 = 2 (the second element), 1+2=3 (the third element) and 1+3=4 (the fourth element) and your vector is only three elements long. There is no fourth element so you get NA. Try (1+1):3. – Mark Miller Jun 07 '14 at 08:19

1 Answers1

15

Because the operator : has precedence over + so 1+1:3 is really 1+(1:3) (i. e. 2:4) and not 2:3. Thus, to change the order of execution as defined operator precedence, use parentheses ()

You can see the order of precedence of operators in the help file ?Syntax. Here is the relevant part:

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.
:: ::: access variables in a namespace
$ @ component / slot extraction
[ [[ indexing
^ exponentiation (right to left)
- + unary minus and plus
: sequence operator
%any% special operators (including %% and %/%)
* / multiply, divide
+ - (binary) add, subtract

Henrik
  • 65,555
  • 14
  • 143
  • 159
plannapus
  • 18,529
  • 4
  • 72
  • 94