R Operators
Operators are the symbols that combine values: +, <, &, <- and so on. R groups them into a few families. Almost all of them are vectorised.
Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 5 + 2 |
7 |
- |
subtraction | 5 - 2 |
3 |
* |
multiplication | 5 * 2 |
10 |
/ |
division | 5 / 2 |
2.5 |
^ |
exponent | 5 ^ 2 |
25 |
%% |
modulus (remainder) | 5 %% 2 |
1 |
%/% |
integer division | 5 %/% 2 |
2 |
When the vectors have different lengths, the shorter one is recycled:
prices <- c(10, 20, 30, 40)
prices * 1.1
prices + c(1, 100) # 1 and 100 are reused
1:6 %% 2 == 0 # which are even?[1] 11 22 33 44
[1] 11 120 31 140
[1] FALSE TRUE FALSE TRUE FALSE TRUE
Assignment operators
<-, =, -> and <<- assign values (see the Variables lesson). Remember that <- is one token: x<-3 means "assign 3", while x < -3 compares with minus three.
Comparison operators
| Operator | Meaning |
|---|---|
== |
equal |
!= |
not equal |
> < |
greater / less than |
>= <= |
greater / less than or equal |
x <- c(4, 7, 7, 2)
x == 7
x != 7
x >= 4
identical(c(1, 2), c(1, 2))[1] FALSE TRUE TRUE FALSE
[1] TRUE FALSE FALSE TRUE
[1] TRUE TRUE TRUE FALSE
[1] TRUE
identical() compares whole objects and returns a single TRUE or FALSE.
Logical operators
!, &, | work element by element; && and || work on single values. See the Booleans lesson for details.
Miscellaneous operators
| Operator | Meaning | Example |
|---|---|---|
: |
integer sequence | 1:5 |
%in% |
membership | 3 %in% c(1, 3) |
%*% |
matrix multiplication | A %*% B |
$ |
element by name | df$col |
[ ], [[ ]] |
indexing | x[2], lst[["a"]] |
|> |
native pipe (R 4.1+) | x |> sqrt() |
~ |
formula | y ~ x |
5:1
fruits <- c("apple", "pear")
c("pear", "plum") %in% fruits
c(1, 4, 9, 16) |> sqrt() |> sum()[1] 5 4 3 2 1
[1] TRUE FALSE
[1] 10
The pipe |> passes the value on its left as the first argument of the call on its right, so the last line reads "take these numbers, then take square roots, then add them up".
Precedence
When an expression mixes operators, R applies them in this order (highest first): ^, unary minus, :, %any% and |>, * /, + -, comparisons, !, & &&, | ||, ->, <-, =.
Two cases surprise almost everyone:
-2 ^ 2 # ^ binds tighter than unary minus
(-2) ^ 2
1:3 * 2 # : binds tighter than *
1:(3 * 2)
n <- 5
1:n-1 # (1:n) - 1, not 1:(n-1)[1] -4
[1] 4
[1] 2 4 6
[1] 1 2 3 4 5 6
[1] 0 1 2 3 4
Tip: When in doubt, add parentheses. They cost nothing and make your intent obvious.
Defining your own operator
Any function whose name is %something% can be used as an infix operator:
`%+%` <- function(a, b) paste(a, b)
"Hello" %+% "R"[1] "Hello R"
Test yourself
What is c(1, 2, 3, 4) + c(10, 20)?
- An error
- 11 22 13 24
- 11 22 3 4
- 30
What does -3 ^ 2 evaluate to?
- 9
- -9
- 6
- -6
What does x |> f() mean?
- f(x)
- x(f)
- x or f
- f is assigned to x