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.
Let’s ask R
to return logical values for certain comparisons:
# using the equal to comparison# this should evaluate to FALSE1 == 2# using the not equal to comparison# this should evaluate to TRUE1 != 2# using the greater than comparison# this should evaluate to FALSE1 > 2# using the less than comparison# this should evaluate to TRUE1 < 2# using the greater than or equal to comparison# this should evavluate to FALSE1 >= 2# using the less than or equal to comparison# this should evaluate to TRUE1 <= 2
We can also compare two given variables. Let’s look at the example below:
# creating variablesx <- 1y <- 2x == y # FALSEx != y # TRUEx > y # FALSEx < y # TRUEx >= y # FALSEx <= y # TRUE
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 <- 1y <- 2# using the if statementif(x == y){print("x is equal to y")}else{print("x is not equal to y")}