Operators in R

In this blog post, we’ll take a look at the most important operators in R – briefly, clearly, and with examples you can try out right away.

Comparison operators: Is it equal? Greater? Less?

In R, you can use special characters to check whether two values are related to each other. Here are the most important ones:

OperatorMeaningExampleResult
==equal5 == 5TRUE
!=not equal5 != 6TRUE
>greater than7 > 5TRUE
<less than3 < 2FALSE
>=greater than or equal to4 >= 4TRUE
<=less than or equal to2 <= 1FALSE

These operators always return either TRUE or FALSE — these are known as logical values, which you can continue working with.


Logical operators: AND, OR, NOT

R wouldn’t be R if you couldn’t also combine conditions. That’s what logical operators are for:

OperatorMeaningExampleResult
&AND5 > 3 & 2 < 4TRUE
``OR5 < 3 | 2 < 4
!NOT!(5 == 5)FALSE

Important: With & and |, the comparison is performed element by element. There are also && and ||, which only check the first element — this is more relevant for if statements.


Applying them to vectors

What makes R special: You can apply these operators directly to vectors. Example:

x <- c(1, 2, 3, 4, 5)
x > 3

This results in:

[1] FALSE FALSE FALSE TRUE TRUE

So you get a vector back indicating which elements are greater than 3.

Even more useful: you can use this for filtering!

x[x > 3]
# Result: 4 5

This makes it easy to extract specific values from a dataset.


Modulo

The modulo operator (%%) returns the remainder of a division.

9%%2
# Result: 1

Conclusion

With these operators, you can already do a lot in R — whether you’re comparing values, formulating conditions, or filtering datasets. Here’s an overview once again:

✅ Comparison operators: ==, !=, <, >, <=, >=
✅ Logical operators: &, |, !
✅ Also works with vectors!