Search code examples
roperator-precedence

In R, why are 1:n-1 ; 1:(n-1) different?


I am a beginner in R. I was wondering why 1:n-1 1:(n-1) would come out different output?

n = 4
1:n-1
[1]0 1 2 3
n = 4
1:(n-1)
[1]1 2 3

Thanks a lot.


Solution

  • It is related to the precedence of operators in R (see https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html)

    enter image description here

    As we can see, : has higher precedence than +- (add, substract), that means 1:n-1 is actually (1:n)-1, which is definitely different from 1:(n-1)