R Comparison Operators

Comparison operators compare two values and return TRUE or FALSE. Every filter, condition check, and decision in R relies on these operators. They answer questions like "Is this score above 80?" or "Are these two values equal?"

All Comparison Operators

Operator   Meaning                   Example       Result
────────────────────────────────────────────────────────────
==         Equal to                  5 == 5        TRUE
!=         Not equal to              5 != 3        TRUE
>          Greater than              7 > 4         TRUE
<          Less than                 3 < 2         FALSE
>=         Greater than or equal     5 >= 5        TRUE
<=         Less than or equal        4 <= 6        TRUE

Common Beginner Mistake: = vs ==

x <- 10       # assignment: stores 10 in x
x == 10       # comparison: asks "is x equal to 10?" → TRUE
x = 10        # also assignment (avoid in comparisons!)

Always use == (double equals) when comparing. Using a single = inside an if condition is a common error that produces unexpected results.

Comparisons With Vectors

temperatures <- c(22, 35, 18, 40, 28, 15)

temperatures > 30
# [1] FALSE  TRUE FALSE  TRUE FALSE FALSE

# Count how many are above 30
sum(temperatures > 30)   # 2

Comparing Strings

R compares character values alphabetically:

"apple" == "apple"   # TRUE
"apple" == "Apple"   # FALSE (case-sensitive!)
"banana" > "apple"  # TRUE  (b comes after a)
"cat" < "dog"        # TRUE  (c before d)

Diagram: Comparison Flow

  Value A    Operator    Value B
     │                      │
     └──────────────────────┘
                │
                ▼
          Compare values
                │
        ┌───────┴────────┐
        ▼                ▼
      TRUE             FALSE
  (condition met)  (condition not met)

Using %in% to Check Membership

The %in% operator checks if a value exists in a group of values:

fruit <- "mango"
fruit %in% c("apple", "mango", "banana")   # TRUE

score <- 72
score %in% c(90, 95, 100)                  # FALSE

Practical Example: Grade Classifier

marks <- c(88, 45, 72, 95, 60, 30)

# Which students passed (marks >= 50)?
passed  <- marks[marks >= 50]
failed  <- marks[marks < 50]

cat("Passed:", passed, "\n")
cat("Failed:", failed, "\n")
cat("Pass count:", length(passed), "\n")

Output:

Passed: 88 72 95 60
Failed: 45 30
Pass count: 4

Comparing NA Values

NA (missing) values require special handling. Comparing NA with == always returns NA, not TRUE or FALSE.

x <- NA
x == NA       # NA  (wrong way!)
is.na(x)      # TRUE (correct way to check for NA)

Use is.na() whenever you need to detect missing values in your data — never use == NA.

Comparison operators power every data filter and condition in R. Whether you are selecting rows from a dataset, validating input, or controlling program flow, these six operators are your primary tools.

Leave a Comment

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