Skip to main content Link Menu Expand (external link) Left Arrow Right Arrow Document Search Copy Copied

Lesson 3b - Logicals (Booleans)

Logicals, otherwise known as booleans, consist of two values: TRUE and FALSE.

Table of Contents

Lesson Objectives

  • Learn what logicals are.
  • Use logical operators.
  • Compare numerical values.

Creating a Logical

In R, TRUE and FALSE are the only two logical values. If you want to create a logical variable, assign the variable to be TRUE or FALSE.

myLogical <- TRUE

Logical Operators

Logicals have their own set of algebraic rules known as Boolean Algebra.

The three most common operations are listed in the table below.

Logical Operator Keyword
AND &
OR |
NOT !

AND

The AND operator results in TRUE if both booleans are already TRUE. Otherwise, it becomes FALSE.

Input

a = TRUE
b = TRUE
c = FALSE

a & b
a & c

Output

[1] TRUE
[1] FALSE

OR

The OR operator results in TRUE if at least one boolean is TRUE. Otherwise, it becomes FALSE.

Input

a = TRUE
b = TRUE
c = FALSE

a | c
c | c

Output

[1] TRUE
[1] FALSE

NOT

The NOT operator reverses the current value. TRUE becomes FASLE, and FALSE becomes TRUE.

Input

a = True
c = False

!a
!c

Output

[1] FALSE
[1] TRUE

Order of Logical Operations

Just like regular algebra, logicals have their own order of operations. The order is listed in the table below. Operations at the top have higher precedence.

Logical Operator Keyword
Brackets ( )
NOT !
AND &
OR |

Numerical Comparisons

We can also compare the values of expressions to generate a boolean as well.

The six comparison operators are shown in the table below.

Comparison Symbol
Less than <
Less than or equal <=
Greater than >
Greater than or equal >=
Equality ==
Inequality !=

Input

5 < 8
2 < 1
3 == 3.0

Output

[1] TRUE
[1] FALSE
[1] TRUE

Key Points / Summary

  • A boolean is a TRUE/FALSE value.
  • &, |, and ~ are three boolean operators.
  • You can compare numerical values.