Skip to main content
HomeTutorialsR Programming

Operators in R

Learn how to use arithmetic and logical operators in R. These binary operators work on vectors, matrices, and scalars.
Mar 2024  · 4 min read

R's binary and logical operators will look very familiar to programmers. Note that binary operators work on vectors and matrices as well as scalars.

Arithmetic Operators

Operator Description
+ addition
- subtraction
* multiplication
/ division
^ or ** exponentiation
x %% y modulus (x mod y) 5%%2 is 1
x %/% y integer division 5%/%2 is 2

Logical Operators

Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
!x Not x
**x y**
x & y x AND y
isTRUE(x) test if X is TRUE
# An example
x <- c(1:10)
x[(x>8) | (x<5)]
# yields 1 2 3 4 9 10

# How it works
x <- c(1:10)
1 2 3 4 5 6 7 8 9 10
x > 8
x < 5
x > 8 | x < 5
1 2 3 4 9 10

Tips for Using Operators in R

Operators play a pivotal role in R programming, allowing for a wide range of operations from basic arithmetic to complex logical evaluations. Here are some tips to ensure you use them effectively and avoid common pitfalls:

1. Be Mindful of Operator Precedence

Just like in mathematics, operators in R have a hierarchy of precedence. For instance, multiplication and division are performed before addition and subtraction. Use parentheses to ensure the desired order of operations.

2. Use Spaces for Clarity

While x+y and x + y are functionally identical, the latter is easier to read. Use spaces around operators to enhance code readability.

3. Double Check == and =

In R, == is a logical operator for comparison, while = can be used for assignment (though <- is more conventional). Ensure you're using the right one for the right task.

4. Avoid Common Pitfalls with Logical Operators

Remember that & and | are element-wise logical operators, while && and || evaluate the first element of a vector and are often used in control structures.

5. Use %in% for Vector Membership

Instead of using multiple OR conditions, you can use the %in% operator to check if an element belongs to a vector or list. For example, x %in% c(1, 2, 3) is more concise than x == 1 | x == 2 | x == 3.

6. Beware of Floating Point Comparisons

Due to the way computers handle floating-point arithmetic, direct comparisons can sometimes yield unexpected results. Instead of x == 0.3, consider using all.equal(x, 0.3) or check if the difference is below a small threshold.

7. Use identical() for Exact Comparisons

When you want to check if two objects are exactly the same, use the identical() function. It's more stringent than == and avoids potential pitfalls with factors or attributes.

8. Remember the Global Assignment Operator <<-

While <- is the standard assignment operator, <<- assigns values globally, even outside the current function or environment. Use it judiciously.

9. Explore Special Operators

R has a rich set of special operators like %/% for integer division or %% for modulus. Familiarize yourself with these to expand your coding toolkit.

10. Stay Updated

R is an evolving language. Stay updated with the latest versions and changes, as new operators or functionalities might be introduced.

By keeping these tips in mind and practicing regularly, you'll be able to harness the full power of operators in R, making your code more efficient, readable, and robust. 

Going Further

To practice working with logical operators in R, try the free first chapter on conditionals of this interactive course.

FAQs about Operators in R

What's the difference between <- and = for assignment in R?

Both <- and = can be used for assignment in R. However, <- is the more traditional and preferred way, especially in scripts and functions. The = operator is often used within function calls to specify named arguments.

Why does 1/3 == 0.3333333 return FALSE in R?

This is due to the way computers handle floating-point arithmetic. Direct comparisons of floating-point numbers can lead to unexpected results because of precision limitations. Instead, consider using all.equal(1/3, 0.3333333) or check if the difference is below a small threshold.

Can I use && and || for vectorized logical operations?

No, && and || are not vectorized. They evaluate only the first element of a vector. For element-wise logical operations on vectors, use & (AND) and | (OR).

How do I check if an element is in a vector or list?

Use the %in% operator. For example, to check if x is in the vector c(1, 2, 3), you'd use x %in% c(1, 2, 3).

What does the %% operator do?

The %% operator returns the modulus (remainder) of a division operation. For instance, 5 %% 2 would return 1, as the remainder of 5 divided by 2 is 1.

How can I perform integer division in R?

Use the %/% operator. For example, 5 %/% 2 returns 2, as 5 divided by 2 yields a quotient of 2.

Why does 2 == "2" return TRUE?

R performs type coercion in certain situations. In this case, it's converting the character "2" to a numeric value for the comparison. However, relying on this behavior can lead to unexpected results. It's always best to ensure data types match before making comparisons.

How do I assign a value globally from within a function?

Use the <<- operator. This assigns the value globally, even outside the current function or environment. However, be cautious with its use, as it can lead to unexpected side effects.

Can I create custom operators in R?

Yes, R allows for the creation of custom infix operators. These operators must start and end with the percentage symbol (%). For example, %myop%. You can then define its behavior like any other function.

How do I ensure exact comparisons between two objects in R?

Use the identical() function. It checks if two objects are exactly the same, considering factors, attributes, and other nuances that == might overlook.



Conditionals and Control Flow in R Tutorial

Learn about relational operators for comparing R objects and logical operators for combining boolean TRUE and FALSE values. You'll also construct conditional statements.
Aditya Sharma's photo

Aditya Sharma

13 min


Matrices in R Tutorial

Learn all about R's matrix, naming rows and columns, accessing elements also with computation like addition, subtraction, multiplication, and division.

Olivia Smith

7 min


Data Types in R

Learn about data types and their importance in a programming language. More specifically, learn how to use various data types like vector, matrices, lists, and dataframes in the R programming language.
Aditya Sharma's photo

Aditya Sharma

12 min


Arrays in R

Learn about Arrays in R, including indexing with examples, along with the creation and addition of matrices and the apply() function.

Olivia Smith

8 min


Utilities in R Tutorial

Learn about several useful functions for data structure manipulation, nested-lists, regular expressions, and working with times and dates in the R programming language.
Aditya Sharma's photo

Aditya Sharma

18 min


Basic Programming Skills in R

Practice basic programming skills in R by using course material from DataCamp's free Model a Quantitative Trading Strategy in R course.
Ryan Sheehy's photo

Ryan Sheehy

5 min

See MoreSee More