1

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.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
codingxxx
  • 37
  • 4
  • 2
    `:` takes the advantage over `-` thus brackets are required to first perform a substraction – Yacine Hajji Sep 26 '22 at 07:37
  • 2
    Operator precedence - `:` has higher precedence than `-` (as a binary operator). – Ritchie Sacramento Sep 26 '22 at 07:38
  • 1
    That's a pitfall you have to be wary of. `:` has (higher) precedence over `-` . So `1:n-1` will first create a vector `1,2,3..n` then subtract 1 from it . Be careful to use parentheses wherever you want want `(n-1)` – R.S. Sep 26 '22 at 07:39

2 Answers2

3

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)

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
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
```

parterre
  • 106
  • 7