What are Booleans/Logical values in R?

Overview

Boolean values in R tell us whether a given expression is TRUE or FALSE. They are used for comparison and relationship between two operands.

For example, 5 is greater than 4, and therefore, the Boolean value for the expression 5 > 4 isTRUE. If otherwise, the return value will be a FALSE.

The table below shows the comparisons available in R:

Operator Description Expression Output
== Equal to 5 == 4 FALSE
!= Not equal to 5 != 4 TRUE
> Greater than 5 > 4 TRUE
< Less than 5 < 4 FALSE
>= Greater than or equal to 5 >= 4 TRUE
<= Less than or equal to 5 <= 4 FALSE

When we compare two values in R, the return value is logical.

Example

Let’s ask R to return logical values for certain comparisons:

# using the equal to comparison
# this should evaluate to FALSE
1 == 2
# using the not equal to comparison
# this should evaluate to TRUE
1 != 2
# using the greater than comparison
# this should evaluate to FALSE
1 > 2
# using the less than comparison
# this should evaluate to TRUE
1 < 2
# using the greater than or equal to comparison
# this should evavluate to FALSE
1 >= 2
# using the less than or equal to comparison
# this should evaluate to TRUE
1 <= 2

Variable based comparisons

We can also compare two given variables. Let’s look at the example below:

# creating variables
x <- 1
y <- 2
x == y # FALSE
x != y # TRUE
x > y # FALSE
x < y # TRUE
x >= y # FALSE
x <= y # TRUE

Comparisons in If/Else statement

We can also use the if statement. The if statement uses the comparison operator to determine if an expression given should be executed or not. Let’s look at the example below:

x <- 1
y <- 2
# using the if statement
if(x == y){
print("x is equal to y")
}else{
print("x is not equal to y")
}

Free Resources