R Logical Operators
Logical operators combine multiple conditions into one. They let you ask compound questions like "Is the age above 18 AND is the account active?" or "Is the score above 90 OR did the student get extra credit?" These operators return TRUE or FALSE based on the combined result.
The Three Core Logical Operators
Operator Name Meaning ──────────────────────────────────────────────────────── & AND Both conditions must be TRUE | OR At least one condition must be TRUE ! NOT Reverses the logical value
AND Operator ( & )
AND requires both sides to be TRUE. If either side is FALSE, the result is FALSE.
age <- 25 income <- 50000 age > 18 & income > 30000 # TRUE & TRUE = TRUE age > 18 & income > 60000 # TRUE & FALSE = FALSE
Truth table: TRUE & TRUE = TRUE TRUE & FALSE = FALSE FALSE & TRUE = FALSE FALSE & FALSE = FALSE
OR Operator ( | )
OR requires only one side to be TRUE. The result is FALSE only when BOTH sides are FALSE.
score <- 45 extra_credit <- TRUE score >= 50 | extra_credit # FALSE | TRUE = TRUE (passes!) score >= 50 | !extra_credit # FALSE | FALSE = FALSE
Truth table: TRUE | TRUE = TRUE TRUE | FALSE = TRUE FALSE | TRUE = TRUE FALSE | FALSE = FALSE
NOT Operator ( ! )
NOT flips the logical value. TRUE becomes FALSE, and FALSE becomes TRUE.
is_weekend <- FALSE !is_weekend # TRUE (it IS a weekday) is_raining <- TRUE !is_raining # FALSE (it is NOT not-raining)
Scalar vs Vectorized Versions
Operator Works On Use In ───────────────────────────────────────────── & Vectors Filtering, comparison | Vectors Filtering, comparison && Single value if() conditions || Single value if() conditions
# Vectorized (element-by-element) c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE) # [1] TRUE FALSE FALSE # Scalar (only first element evaluated) c(TRUE, FALSE) && c(TRUE, TRUE) # [1] TRUE
Practical Example: Loan Eligibility
age <- 32
salary <- 45000
credit <- 720
eligible <- age >= 21 & salary >= 25000 & credit >= 700
if (eligible) {
cat("Loan approved\n")
} else {
cat("Loan not approved\n")
}
Output:
Loan approved
Combining Multiple Conditions
x <- 15 # Is x between 10 and 20? x > 10 & x < 20 # TRUE # Is x outside the 10–20 range? x < 10 | x > 20 # FALSE # Is x NOT equal to 15? !(x == 15) # FALSE x != 15 # FALSE (same result, simpler form)
Logical operators are the glue that holds complex conditions together. Every meaningful data filter in R — selecting specific rows, validating conditions, controlling program behavior — uses at least one of these operators.
