0

Consider this vector:

x <- c("A", "B", "C", "D")

When we do a normal slice,

x <- x[2:4]

It returns:

"B" "C" "D"

Why is it that when we perform this line of code, NA is returned?

x[1+1:4]
"B" "C" "D" NA 

However when we put a parenthesis around the plus sign,

x[(1+1):4]
[1] "B" "C" "D"

It returns the correct output.

Javier
  • 730
  • 4
  • 17
  • 5
    check the output of `1+1:4` and `(1+1):4` – Ronak Shah Jan 17 '19 at 08:31
  • 4
    Here, the `:` operator **by convention** signifies a stronger bond than `+`. Therefore, the first vector could also have been written as `1+1, 1+2, 1+3, 1+4` because `1+...` applies to all elements of the vector. Compare this to addition/ subtraction vs. multiplication/ division in mathematics. – Roman Jan 17 '19 at 08:33
  • 1
    Read about [Operator Syntax and Precedence](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html) – zx8754 Jan 17 '19 at 08:48

1 Answers1

1

You are slicing with two different set of indexes.

In the first case 1+1:4 you are producing a vector that goes from 1 to 4, 1:4 and then 1 is added, hence 2,3,4,5. In your vector the 5th position does not exist so you get an NA.

In the second vector you are slicing taking the positions (1+1):4 which corresponds to 2,3,4. This are all elements that exist in your initial vector and so you have the corresponding values

Marco De Virgilis
  • 982
  • 1
  • 9
  • 29