R Logical Operators
Logical Operators
As with comparison operators, the result of a logical operator is TRUE or FALSE.
Logical operators are used to combine conditions. For example, to check if a number is between 3 and 10, it must be greater than 3 and less than 10:
Example
x <- 5
x > 3 & x < 10
Try it Yourself »
A list of the logical operators:
| Operator | Name | Example | Description | Try it |
|---|---|---|---|---|
| & | AND | x > 3 & x < 10 | Returns TRUE if both conditions are TRUE | Try it » |
| | | OR | x > 3 | x > 10 | Returns TRUE if at least one of the conditions is TRUE | Try it » |
| ! | NOT | !(x > 3 & x < 10) | Reverses the result: TRUE becomes FALSE, and FALSE becomes TRUE | Try it » |
This table shows the result of & and | for all combinations of two values:
| a | b | a & b | a | b |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE | TRUE |
| FALSE | TRUE | FALSE | TRUE |
| FALSE | FALSE | FALSE | FALSE |
&& and ||
R also has && and ||. They work like & and |, but only with one value on each side. They are mostly used in if statements, which you will learn about in the If...Else chapter:
Example
x <- 5
x > 3 && x < 10
x > 10 || x == 5
Try it Yourself »
& and | can compare many values at once. Here, R compares the first values, then the second values, and then the third values:
Example
c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE)
Try it Yourself »
You will learn more about c() in the Vectors chapter.
Real-Life Example: Login Check
Logical operators are often used to check access rights, for example on a website:
Example
is_logged_in <- TRUE
is_admin <- FALSE
is_logged_in & !is_admin
is_logged_in | is_admin
!is_logged_in
Try it Yourself »
is_logged_in & !is_adminisTRUE: the user is logged in, and is not an admin, so it is a regular user.is_logged_in | is_adminisTRUE: at least one of them isTRUE, so the user has access.!is_logged_inisFALSE: the user is logged in.