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.
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.
It is related to the precedence of operators in R (see https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html)
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)
You need to put n-1
into brackets if you want it to be evaluated first, as :
is binding stronger than -
. 1:n-1
evaluates 1:n
first and then subtracts 1 from each element.
In your example, 1:n
yields
[1] 1 2 3 4
```
Subtraction by 1 yields:
```
[1] 0 1 2 3
```