The Ultimate Guide to Relational Operators in R (2024)

Relational operators, or comparators, are operators that help us see how one R object relates to another.

4 Types of Relational Operators in R

  1. Equality operator: ==
  2. Inequality operator: !=
  3. Less than/greater than operator: < and >
  4. Less than or equal to/greater than or equal to operator: <= and >=

Equality Operator ==

You can check whether two objects are equal (equality) by using a double equals sign==.

We can see if the logical value of TRUE equals the logical value of TRUE by using this query TRUE == TRUE. The result of the equality query is a logical value ( TRUE or FALSE). In this case, it’s TRUE because TRUE equals TRUE.

On the contrary, TRUE == FALSE will give us FALSE.

Apart from logical variables, we can also check the equality of other types, such as strings and numbers.

# Comparing the equality of two strings"hello" == "goodbye"# Comparing the equality of two numbers3 == 2

Both of these output FALSE.

The Ultimate Guide to Relational Operators in R (1)

More on Data Science: 6 Types of Data Analysis

Equality Operator Examples

The most basic form of comparison is equality. Recall that it’s represented by the double equation sign syntax, ==. Here is an example of some equality statements:

3 == (2 + 1)"ultimate guide" == "r"TRUE == FALSE"Rchitect" == "rchitect"
The Ultimate Guide to Relational Operators in R (2)

Notice that R is case sensitive: “R” is not equal to “r.”

Try the following comparisons:

  • Write R code to see if TRUE equals FALSE.
  • Check to see if -6 * 14 is equal to 17 — 101.
  • See if the strings "useR" and "user" are equal in R.
  • Find out what happens if you compare TRUE to the numeric 1.

Make sure not to mix up == (comparison) and = (assignment), as == is what’s used to check equality of R objects.

Solution

# Comparison of logicalsTRUE == FALSE# Comparison of numerics(-6 * 14) == (17 - 101)# Comparison of character strings"useR" == "user"# Comparison of a logical with a numericTRUE == 1
The Ultimate Guide to Relational Operators in R (3)

The Inequality Operator !=

The opposite of the equality operator is the inequality operator, written as an exclamation mark followed by an equals sign ( != ).

For example, the sentence "hello" != "goodbye" would read as: “hello” is not equal to “goodbye.” Because this statement is correct, R will output TRUE.

The inequality operator can also be used for numerics, logicals and other R objects.

# Output FALSETRUE != TRUE# Output TRUETRUE != FALSE# Output TRUE"hello" != "goodbye"# Output TRUE3 != 2

The result of the equality operator is the opposite for the inequality operator.

The Ultimate Guide to Relational Operators in R (4)

Inequality Operator Example

The inequality comparator is the opposite of equality. The following statements all evaluate to TRUE :

3 == (2 + 1)"intermediate" != "r"TRUE != FALSE"Rchitect" != "rchitect"

Write out expressions that do the following:

  • Check if TRUE equals FALSE.
  • Check if — 6 * 14 is not equal to 17 — 101.
  • Check if the strings “useR” and “user” are different.
  • Check if TRUE and 1 are equal.

Solution

# Comparison of logicalsTRUE == FALSE# Comparison of numerics(-6 * 14) != (17-101)# Comparison of character strings"useR" != "user"# Compare a logical with a numericTRUE == 1
The Ultimate Guide to Relational Operators in R (5)

Less Than and Greater Than Operators < and >

There are also situations where we need more than equality and inequality operators. For instance, what about checking if an R object is “less than” or “greater than” another R object? In this case, we can use the less than < and greater than > sign for this.

In the case of numerical values, this is pretty straightforward. For example, three is less than five, so 3 < 5 will evaluate to TRUE, while three is greater than five so 3 > 5 will evaluate to FALSE.

For numerics, this makes sense. But how would this work for character strings and logical values?

For character strings, R uses the alphabet to sort them. So, "Hello" > "Goodbye" would evaluate to TRUE since “H” comes after “G” in the alphabet, and R considers it greater.

For logical values, TRUE corresponds to 1, and FALSE corresponds to 0. So, is TRUE less than FALSE? No, because 1 is not less than 0, hence the FALSE result.

The Ultimate Guide to Relational Operators in R (6)

The Less Than or Equal To, and Greater Than or Equal To Operators <= and >=

We can also check to see if one R object is greater than or equal to (or less than or equal to) another R object. To do this, we can use the less than sign or the greater than sign together with the equals sign.

So, we can write five is greater than or equal to three 5 >= 3, as well as three is greater than or equal to three 3 >= 3, which will evaluate as TRUE.

The Ultimate Guide to Relational Operators in R (7)

Less Than and Greater Than or Equal To Operator Examples

Apart from equality operators ( == and != ), we also learned about the less than and greater than operators: < and >. We can also add an equal sign to express less than or equal to or greater than or equal to, respectively. For example, the following all evaluate to FALSE:

(1+2) > 4"dog" < "Cats"TRUE <= FALSE

Remember that for string comparison, R determines the greater than relationship based on alphabetical order. Also keep in mind that TRUE is treated as 1 for arithmetic, and FALSE is treated as 0. Therefore, FALSE < TRUE is TRUE .

Write R expressions to check whether:

  • -6 * 5 + 2 is greater than or equal to -10 + 1.
  • “raining” is less than or equal to “raining dogs”
  • TRUE is greater than FALSE.

Solution

# Comparison of numerics(-6 * 5 + 2) >= (-10 + 1)# Comparison of character strings"raining" <= "raining dogs"# Comparison of logicalsTRUE > FALSE
The Ultimate Guide to Relational Operators in R (8)

Relational Operators and Vectors

We already know that R is pretty good with vectors. Without having to change anything about the syntax, R’s relational operators also work on vectors.

Suppose you’ve recorded the daily number of views your LinkedIn profile had in the previous link, and you stored them in a vector, linkedin.

linkedin <- c(16, 9, 13, 5, 2, 17, 14)

If we want to find out on which days the number of views exceeded 10, we can use the greater than sign.

linkedin > 10
The Ultimate Guide to Relational Operators in R (9)

The first, third, sixth and seventh element in the vector all have views greater than 10. So, for these elements the result will be TRUE.

We can also compare vectors to vectors. Suppose you also recorded the number of views your Facebook profile had the previous week and saved them in another vector facebook.

facebook <- c(17, 7, 5, 16, 8, 13, 14)

When are the number of Facebook views less than or equal to the number of LinkedIn views? We can use the following expression to calculate this.

facebook <= linkedin

In this case, the comparison is done for every element of the vector, one at a time. For example, on the third day, the number of Facebook views is five, and the number of LinkedIn views is 13. The comparison evaluates to TRUE, as five is smaller than or equal to 13. This means that the number of Facebook views is less than or equal to the number of LinkedIn views on the third day.

The Ultimate Guide to Relational Operators in R (10)

Relational Operators in Vectors Example

Using the same social media vectors above, linkedin and facebook, which contain the number of profile views over the last seven days, use relational operators to find a logical answer ( TRUE or FALSE ) for the following questions:

  • On which days did the number of LinkedIn profile views exceed 15?
  • When was your LinkedIn profile viewed only five times or fewer?
  • When was your LinkedIn profile visited more often than your Facebook profile?
# The linkedin and facebook vectorslinkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)

Solution

# The linkedin and facebook vectorslinkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)# Popular dayslinkedin > 15# Quiet dayslinkedin <= 5# LinkedIn more popular than Facebooklinkedin > facebook
The Ultimate Guide to Relational Operators in R (11)

From the output, we can determine the following:

  • Your LinkedIn profile views exceed 15 on the first and sixth day.
  • Your LinkedIn profile was only viewed five or less times on the fourth and fifth day.
  • Your LinkedIn profile was visited more than your Facebook profile on the second, third and sixth day.

More on Data Science: Tackling Jump Game Problems on LeetCode

Challenge: Compare Matrices

Up to now, we’ve learned and compared logicals, numerics, strings and vectors. However, R’s ability to deal with different data structures for comparisons does not stop at matrices. Matrices and relational operators also work together seamlessly.

Instead of using vectors, suppose the LinkedIn and Facebook data is stored in a matrix called views. The first row contains the LinkedIn information, and the second row the Facebook information.

# The social data stored in a matrixlinkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)

Using the relational operators you’ve learned, try to determine the following:

  • When were the views exactly equal to 13? Use the views matrix to return a logical matrix.
  • For which days were the number of views less than or equal to 14? Again, have R return a logical matrix.

Solution

# The social datalinkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)# When does views equal 13?views == 13# When is views less than or equal to 14?views <= 14
The Ultimate Guide to Relational Operators in R (12)

From the output we can determine:

  • On day three, there were 13 LinkedIn views. On day six, there were 13 Facebook views.
  • On days two, three, four, five and seven, there were less than or equal to 14 LinkedIn views. On days two, three, five, six and seven there were less than or equal to 14 Facebook views.
The Ultimate Guide to Relational Operators in R (2024)

FAQs

What is %*% in R? ›

The %in% operator returns TRUE if the left argument is in the vector to the right. The %*% operator performs matrix multiplication on two matrices.

How many relational operators are there in R? ›

The relational operators (also known as logical binary operators) include == , != , < , <= , > and >= . The output of a condition is a logical vector TRUE or FALSE .

What value do relational operators always return a an ______? ›

Truth value: A syntax using relational operators always returns a Boolean value as output, which can be either True or False. Short circuit Evaluation: An expression may not be evaluated completely if the result is already known. For instance, x<y & x>z is evaluated only if x<y is True.

What is the equal operator in R? ›

Comparison operators in R include: Equal to == Not equal to != Greater than >

What does %>% in R mean? ›

R pipes are a way to chain multiple operations together in a concise and expressive way. They are represented by the %>% operator, which takes the output of the expression on its left and passes it as the first argument to the function on its right. Using pipes in R allows us to link a sequence of analysis steps.

What does %% in R mean? ›

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.

What are the 6 relational operators? ›

Relational Operators (<, >, =, <=, >=, !=)
SymbolOperationDescription
<Less thanTrue if x is less than y.
>=Greater than or equal toTrue if x is greater than or equal to y.
<=Less than or equal toTrue if x is less than or equal to y.
!=Not equal toTrue if x is not equal to y.
2 more rows

What does '|' mean in R? ›

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators.

What are the 8 relational set operators? ›

Relational Algebra defines the theoretical foundation of manipulating table content using the eight relational operators: SELECT, PROJECT, JOIN, INTERSECT, UNION, DIFFERENCE, PRODUCT, AND DIVIDE.

What is the result of relational operators always? ›

These relational operators always result in false or true. Equality ( == ) first compares the type of its operands. If the types are different, then the result is false. Otherwise, the values of the operands are compared.

What do relational operators allow you to do with numbers? ›

The relational operators are often used to create a test expression that controls program flow. This type of expression is also known as a Boolean expression because they create a Boolean answer or value when evaluated.

What is the output of relational operators? ›

Mathabo Poopedi The output of the relational operator is (true/false) boolean value, and in Java, true or false is a non-numeric value that is not related to zero or one.

How to create a vector in R? ›

A vector can be created using an in-built function in R called c(). Elements must be comma-separated.

How to print data in R? ›

To display ( or print) a text with R, use either the R-command cat() or print(). Note that in each case, the text is considered by R as a script, so it should be in quotes. Note there is subtle difference between the two commands so type on your prompt help(cat) and help(print) to see the difference.

What is double () in R? ›

double creates a double-precision vector of the specified length. The elements of the vector are all equal to 0 . It is identical to numeric . as. double is a generic function.

What is the use of (*)? ›

The operators like multiplication and power are generally known to us that can be done using this asterisk(*). In different circ*mstances, it can carry out additional operations like unpacking and a variable number of arguments passing, etc.

What does the asterisk do in R? ›

an asterisk, “*“, matches zero or more times, a character is optional but also may be repeated. a plus, “+”, matches one or more times, a character is required and may be repeated. braces with a number, “{n}” matches exactly n times.

Why do you put * before a variable? ›

When you declare a variable with *, it means you're creating what's called a pointer variable. A pointer points to a memory address holding a value, rather than the value itself.

What is the meaning of R * maths? ›

In mathematics, R* refers to the extended real number line which includes positive and negative infinity along with all real numbers. It's denoted by the symbol ∞.

References

Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 5873

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.