Labs ICT
⭐ Pro Login

Booleans

2 min read | R Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Booleans — TRUE and FALSE — are the building blocks of logic in R. Every comparison, every condition, every filter boils down to a boolean. They seem simple, but they're the engine behind almost every decision your code makes.

TRUE and FALSE

The two logical values in R are TRUE and FALSE. They must be uppercase. You can also use T and F as shortcuts, but be careful — T and F are just variables that default to TRUE and FALSE. If you accidentally reassign them, you'll break things. Stick with the full uppercase versions.


# The logical values
is_sunny <- TRUE
is_raining <- FALSE
print(is_sunny)
print(is_raining)
    

Comparison Operators

Comparisons produce booleans. >, <, >=, <=, == (equal to), != (not equal to) — they all return TRUE or FALSE. The double equals == is especially important because a single = means assignment. Mixing them up is a classic R gotcha.


# Comparisons
5 > 3
10 <= 7
"apple" == "orange"
"apple" != "orange"
    

Logical Operators: &, |, !

You can combine booleans with logical operators. & means AND (both must be TRUE), | means OR (at least one must be TRUE), and ! means NOT (flips TRUE to FALSE). These let you build more complex conditions.


# Logical combinations
TRUE & TRUE
TRUE & FALSE
TRUE | FALSE
FALSE | FALSE
!TRUE
!(5 > 3)
    

any() and all()

When you have a vector of booleans, any() returns TRUE if at least one value is TRUE, and all() returns TRUE only if every value is TRUE. These are incredibly useful for checking conditions across datasets.


# Checking multiple values at once
scores <- c(85, 90, 78, 92)
any(scores > 90)
all(scores > 75)
all(scores > 80)
    

Booleans might feel too simple at first, but they're everywhere in R. Filtering rows, checking conditions, running loops — it's all booleans under the hood. Get comfortable with them and everything else gets easier.