R Academy · Lesson

Logical Operators and Boolean Logic

Understand &, |, !, xor(), any(), and all() for Boolean operations.

Lesson 2 of 413 steps

Logical Operators and Boolean Logic is a free R Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.

Introduction to Boolean Logic

Boolean logic is the foundation of decision-making in programming. In R, logical values are TRUE and FALSE. Logical operators combine these values to form complex conditions.

# Boolean values in R
is_raining <- TRUE
is_cold <- FALSE
cat('Is raining:', is_raining, '
')
cat('Is cold:', is_cold, '
')
cat('Class:', class(is_raining), '
')

Element-wise AND with &

The & operator performs element-wise AND on vectors. It returns TRUE only when both corresponding elements are TRUE. It processes every element in a vector.

ages <- c(15, 22, 17, 30, 19)
has_id <- c(FALSE, TRUE, FALSE, TRUE, TRUE)

# Can buy alcohol? (must be 18+ AND have ID)
can_buy <- (ages >= 18) & has_id
cat('Ages >= 18:', ages >= 18, '
')
cat('Has ID:', has_id, '
')
cat('Can buy:', can_buy, '
')

Element-wise OR with |

The | operator performs element-wise OR. It returns TRUE when at least one of the corresponding elements is TRUE.

scores_math <- c(85, 45, 72, 38, 90)
scores_english <- c(40, 88, 65, 70, 55)

# Pass if either subject >= 60
passes <- (scores_math >= 60) | (scores_english >= 60)
cat('Math pass:', scores_math >= 60, '
')
cat('English pass:', scores_english >= 60, '
')
cat('Overall pass:', passes, '
')

Logical NOT with !

The ! operator negates a logical value, flipping TRUE to FALSE and vice versa. It is applied before & and | in evaluation order.

is_weekend <- c(TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE)
cat('Is weekend:', is_weekend, '
')
cat('Is weekday:', !is_weekend, '
')

# Count weekdays
cat('Number of weekdays:', sum(!is_weekend), '
')

Scalar AND with &&

&& is the scalar version of AND — it only evaluates the first element of each vector and uses short-circuit evaluation: if the left side is FALSE, the right side is never evaluated.

x <- 10

# Short-circuit: second condition skipped if first is FALSE
if (x > 0 && x < 100) {
  cat('x is a positive double-digit or less
')
}

# && only looks at first element
cat('TRUE && FALSE:', TRUE && FALSE, '
')
cat('TRUE & FALSE (vectorised):', TRUE & FALSE, '
')

Scalar OR with ||

|| is the scalar version of OR with short-circuit evaluation: if the left side is TRUE, the right side is never evaluated. Use || in if statements where you only need a single result.

user_role <- 'admin'

# Short-circuit OR — stops at first TRUE
if (user_role == 'admin' || user_role == 'superuser') {
  cat('Access granted
')
} else {
  cat('Access denied
')
}

cat('FALSE || TRUE:', FALSE || TRUE, '
')

Exclusive OR with xor()

xor(x, y) returns TRUE when exactly one of x or y is TRUE. It returns FALSE when both are the same. Useful for toggle logic.

# xor truth table
cat('xor(TRUE, TRUE):', xor(TRUE, TRUE), '
')   # FALSE
cat('xor(TRUE, FALSE):', xor(TRUE, FALSE), '
')  # TRUE
cat('xor(FALSE, TRUE):', xor(FALSE, TRUE), '
')  # TRUE
cat('xor(FALSE, FALSE):', xor(FALSE, FALSE), '
') # FALSE

# Practical: exactly one sensor triggered
sensor_a <- c(TRUE, FALSE, TRUE, FALSE)
sensor_b <- c(FALSE, FALSE, TRUE, TRUE)
cat('Exactly one sensor:', xor(sensor_a, sensor_b), '
')

any() and all()

any() returns TRUE if at least one element is TRUE. all() returns TRUE only if every element is TRUE. Both collapse a logical vector to a single value.

temperatures <- c(22.1, 24.5, 19.8, 31.2, 28.0)

cat('Any temperature above 30?', any(temperatures > 30), '
')
cat('All temperatures above 15?', all(temperatures > 15), '
')
cat('All temperatures above 25?', all(temperatures > 25), '
')

# Useful for data validation
test_scores <- c(78, 85, 92, 88, 76)
cat('All passed (>=60)?', all(test_scores >= 60), '
')

Combining Logical Operators

You can chain multiple logical operators to build complex conditions. R evaluates ! first, then &, then |. Use parentheses to make your intent clear.

age <- 25
income <- 55000
credit_score <- 720

# Loan eligibility: age 21-65, income >= 40000, credit >= 700
eligible <- (age >= 21 && age <= 65) &&
            (income >= 40000) &&
            (credit_score >= 700)
cat('Loan eligible:', eligible, '
')

Logical Operators on Data Frames

Logical operators shine when filtering data frames. You can combine multiple conditions to select exactly the rows you need.

# Simple data frame
names_vec <- c('Alice', 'Bob', 'Carol', 'Dave', 'Eve')
ages_vec <- c(28, 35, 22, 45, 31)
salaries <- c(55000, 72000, 38000, 90000, 61000)

# Filter: age 25-40 AND salary above 50000
mask <- (ages_vec >= 25 & ages_vec <= 40) & (salaries > 50000)
cat('Matching employees:', names_vec[mask], '
')

Boolean Arithmetic

In R, TRUE is treated as 1 and FALSE as 0 in arithmetic. This means you can use sum() to count TRUE values and mean() to get the proportion.

responses <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE)

cat('Number of TRUE:', sum(responses), '
')
cat('Proportion TRUE:', mean(responses), '
')
cat('Percentage:', mean(responses) * 100, '%
')

# Count values meeting a condition
scores <- c(88, 45, 92, 61, 73, 55, 84)
cat('Number passing (>=60):', sum(scores >= 60), '
')

Quick Check

What is the difference between & and && in R?

Recap: Boolean Logic in R

Excellent! Here are the key takeaways from this lesson:

  • & and | are vectorised — they compare element-by-element
  • && and || are scalar with short-circuit evaluation — use in if statements
  • ! negates a logical value
  • xor() returns TRUE when exactly one argument is TRUE
  • any() and all() collapse logical vectors to a single value
  • TRUE == 1 and FALSE == 0, so you can sum or average logical vectors
# Summary: all logical operators at a glance
x <- c(TRUE, FALSE, TRUE)
y <- c(TRUE, TRUE, FALSE)
cat('x & y :', x & y, '
')
cat('x | y :', x | y, '
')
cat('!x    :', !x, '
')
cat('xor   :', xor(x, y), '
')
cat('any(x):', any(x), '
')
cat('all(x):', all(x), '
')
Free to start

Learn R with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
43
Lessons
159

Frequently Asked Questions

Is the “Logical Operators and Boolean Logic” lesson free?

Yes — any 3 lessons of the R Academy learning path, including “Logical Operators and Boolean Logic”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.

What will I learn in “Logical Operators and Boolean Logic”?

Understand &, |, !, xor(), any(), and all() for Boolean operations. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Logical Operators and Boolean Logic” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Arithmetic and Comparison Operators
  2. Logical Operators and Boolean Logic
  3. Assignment and Special Operators
  4. Operator Precedence and Complex Expressions
← Back to R Academy