Chapter 16: R Booleans / Logical Values

R: Booleans / Logical Values.

These are the yes/no, true/false values that control almost everything in data analysis:

  • Which rows to keep or remove
  • Which calculations to perform
  • Which points to color red in a plot
  • Whether a condition is met
  • Loop control, function behavior, error checking…

Let’s go through this slowly and thoroughly — like I’m sitting next to you in RStudio, showing every line live.

1. What Are Logical Values in R? (The Basics)

R has only two possible logical values:

  • TRUE
  • FALSE

They must be written in uppercase — true, True, tRuE will not work.

R

Short aliases (very common in code):

  • T = TRUE
  • F = FALSE
R

→ Many experienced people use T/F in quick interactive work, but in scripts/packages write TRUE/FALSE for clarity and safety.

2. Where Do Logical Values Come From? (The Most Common Source)

99% of logical values are created by comparisons — not typed by hand.

Comparison operators:

Meaning Operator Example Result
Equal == 5 == 5 TRUE
Not equal != Hyderabad != “Bengaluru” TRUE
Greater than > temp > 30 TRUE/FALSE
Greater or equal >= marks >= 40
Less than < age < 18
Less or equal <= score <= 100

Real Hyderabad examples:

R

3. Logical Operations – Combining Conditions (AND, OR, NOT)

These are the logical operators — they combine multiple TRUE/FALSE values.

Meaning Operator Symbol Example code Result
AND & & (temp > 28) & (humidity > 60) TRUE if both true
OR (marks < 40)
NOT ! ! !is_raining Opposite
AND (scalar) && && if (x > 0 && y > 0) { ... } Used in if() conditions (single value only)
OR (scalar) || || if (error

Important difference:

  • & and → vectorized → work element-by-element on vectors
  • && and || → single logical only → used inside if() / while()
R

4. Logical Values in Real Work – Filtering & Summaries

This is where they become super powerful.

R

5. Missing Values (NA) & Logical Operations

NA is special — logical operations with NA usually give NA

R

6. Quick Cheat-Sheet – Logical Essentials

  • Values → TRUE, FALSE (or T, F)
  • Comparisons → == != > >= < <=
  • Combine → & (and), (or), ! (not)
  • Vectorized → & and Single-value → && and || (inside if())
  • Use in filtering → df[logical_vector, ]
  • Count → sum(logical_vec), mean(logical_vec)
  • Opposite → !logical_vec or logical_vec == FALSE

Your Mini Practice (Copy → Run Right Now!)

R

Output something like:

text

Feel comfortable with logical values now?

Next questions?

  • Want to practice complex filtering with multiple conditions?
  • How logical values work inside dplyr (filter(), mutate(), if_else())?
  • Or move to factors / vectors / subsetting?

Just tell me — whiteboard is ready! ☕🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *