upgrade
upgrade

๐Ÿ’ปIntro to Programming in R

R Logical Operators

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Logical operators are the decision-making engine of your R code. Every time you filter a dataset, write a conditional statement, or subset rows based on criteria, you're relying on these operators to evaluate what's TRUE and what's FALSE. You're being tested on your ability to construct conditions, combine multiple criteria, and predict the output of logical expressionsโ€”skills that show up constantly in data manipulation and control flow questions.

Think of logical operators as falling into three categories: comparison operators (checking relationships between values), Boolean operators (combining conditions), and membership operators (checking if values belong to sets). Don't just memorize the symbolsโ€”know when to use & versus |, understand why == isn't the same as =, and recognize how these operators behave with vectors. That conceptual understanding is what separates students who can debug code from those who get stuck.


Comparison Operators: Testing Relationships Between Values

These operators compare two values and return a logical result. They work element-wise on vectors, meaning R compares each element in position and returns a vector of TRUE/FALSE values.

== (Equal To)

  • Tests exact equality between two valuesโ€”returns TRUE only when both sides match perfectly
  • Works across data types including numeric, character, and logical values (but be careful comparing floats due to precision issues)
  • Vectorized behavior means c(1, 2, 3) == 2 returns FALSE TRUE FALSE, not a single value

!= (Not Equal To)

  • Returns TRUE when values differโ€”the logical opposite of ==
  • Essential for filtering when you want to exclude specific values from a dataset
  • Combines with subsetting like df[df$category != "exclude", ] to remove unwanted rows

> (Greater Than)

  • Strict inequality testโ€”returns TRUE only when the left value exceeds the right
  • Does not include equality so 5 > 5 returns FALSE
  • Commonly paired with if statements and while loops for threshold-based logic

< (Less Than)

  • Mirror of greater thanโ€”returns TRUE when the left value is smaller
  • Useful for range filtering when combined with other operators
  • Works with character strings using alphabetical ordering (lexicographic comparison)

Compare: > vs. >=โ€”both test magnitude, but >= includes the boundary value while > excludes it. If an exam question asks about "at least 5" or "5 or more," you need >=, not >.

>= (Greater Than or Equal To)

  • Inclusive upper comparisonโ€”returns TRUE when the left value is greater than or exactly equal to the right
  • Critical for boundary conditions in statistical thresholds and data validation
  • Equivalent to (x > y) | (x == y) but more efficient and readable

<= (Less Than or Equal To)

  • Inclusive lower comparisonโ€”returns TRUE when the left value is smaller than or equal to the right
  • Frequently used in loops with conditions like while(i <= n) to include the final iteration
  • Pairs naturally with >= when defining inclusive ranges like x >= 5 & x <= 10

Compare: == vs. =โ€”this is a classic error. == tests equality and returns TRUE/FALSE, while = is an assignment operator. Writing if(x = 5) will assign 5 to x, not test whether x equals 5.


Boolean Operators: Combining Conditions

These operators take logical values as input and return logical values as output. They let you build complex conditions from simpler ones, which is essential for multi-criteria filtering.

& (Logical AND)

  • Requires both conditions to be TRUEโ€”returns FALSE if either side is FALSE
  • Element-wise on vectors so c(TRUE, FALSE) & c(TRUE, TRUE) returns TRUE FALSE
  • Use for intersection logic like "rows where age > 18 AND income > 50000"

| (Logical OR)

  • Requires at least one condition to be TRUEโ€”only returns FALSE when both sides are FALSE
  • More permissive than ANDโ€”expands rather than restricts your selection
  • Use for union logic like "rows where region is East OR region is West"

Compare: & vs. |โ€”AND narrows your results (both conditions must pass), while OR broadens them (either condition can pass). When filtering data, & typically returns fewer rows than |. Remember: & is restrictive, | is permissive.

! (Logical NOT)

  • Flips the logical valueโ€”TRUE becomes FALSE and vice versa
  • Placed before the condition like !is.na(x) to find non-missing values
  • Essential for negation when you want "everything except" a certain condition

Compare: & and | vs. && and ||โ€”the single versions (&, |) are vectorized and compare element-by-element. The double versions (&&, ||) only evaluate the first element and use short-circuit evaluation. Use single for data filtering, double for control flow in if statements.


Membership Operators: Checking Set Inclusion

This operator tests whether values belong to a defined set, which is more readable and efficient than chaining multiple == comparisons with |.

%in% (Value Matching)

  • Tests membership in a vectorโ€”returns TRUE if the left value appears anywhere in the right vector
  • Vectorized on the left side so c(1, 2, 5) %in% c(1, 2, 3) returns TRUE TRUE FALSE
  • Cleaner than alternatives since x %in% c("a", "b", "c") replaces x == "a" | x == "b" | x == "c"

Compare: %in% vs. chained == with |โ€”both can test multiple values, but %in% is more readable and less error-prone. For filtering rows where a column matches any of several values, always prefer %in%.


Quick Reference Table

ConceptBest Examples
Equality testing==, !=
Magnitude comparison (strict)>, <
Magnitude comparison (inclusive)>=, <=
Combining conditions (restrictive)&
Combining conditions (permissive)`
Negating conditions!
Set membership%in%
Common errors to avoid= vs. ==, & vs. &&

Self-Check Questions

  1. What is the difference between & and && in R, and when would you use each one?

  2. Given x <- c(3, 7, 2, 9), what does x > 5 & x < 10 return, and why?

  3. Compare and contrast x == 5 | x == 8 | x == 12 with x %in% c(5, 8, 12)โ€”when would you prefer one over the other?

  4. If you want to filter a dataframe to include rows where age >= 21 AND status != "inactive", write the logical expression you would use inside the subset brackets.

  5. What does !(x > 5) return when x <- c(3, 5, 7), and how does this differ from x <= 5?