Typing in 0-2:-4
returns [1] -2 -1 0 1 2 3 4
in the console. Can anyone explain the logic behind this?
Asked
Active
Viewed 85 times
2

Rich Scriven
- 97,041
- 11
- 181
- 245

Andreas Wolters
- 29
- 2
-
2It's in the R-FAQ (sort of): See section 7.33 and ?Syntax. Your expression is being interpreted as 0 minus seq( 2, -4). The unary "-"-operator has higher precedence than the "colon" and the colon ":"-operator has higher precedence than a binary minus. – IRTFM Feb 01 '17 at 18:34
-
Just a general note - if you something isn't doing what you expect and you post here it wouldn't hurt to tell us what you expect. I see your code and know how R deals with these things so in my mind it looks exactly like it should. This is a simple example and it's easy enough to figure out what you probably intended it to do but if you're asking a question it is a good idea to clarify what your expectations were. – Dason Feb 01 '17 at 18:47
1 Answers
7
Because of the order of operation:
0 - (2:-4)
which expands to
0 - c(2, 1, 0, -1, -2, -3, -4)
See ?Syntax
for more details, including a complete list of binary operators in order of precedence.

Gregor Thomas
- 136,190
- 20
- 167
- 294

r2evans
- 141,215
- 6
- 77
- 149
-
Good edit, thanks @Gregor. (Don't think I've actually read that page yet ... :-) – r2evans Feb 01 '17 at 18:33