R Comparison Operators

Comparison operators let you test how two values relate to each other, returning TRUE or FALSE — the foundation for filtering data and controlling program flow in R.

The Comparison Operators

Each comparison operator takes two values and answers a yes-or-no question about them, producing a single logical value: TRUE or FALSE. These are case-sensitive and type-aware, so comparing text uses exact character matching.

OperatorMeaningExampleResult
==Equal to5 == 5TRUE
!=Not equal to5 != 3TRUE
<Less than3 < 5TRUE
>Greater than3 > 5FALSE
<=Less than or equal to5 <= 5TRUE
>=Greater than or equal to4 >= 5FALSE

Basic Comparisons

5 == 5
5 != 3
"apple" == "Apple"

Comparing Vectors

Just like arithmetic operators, comparison operators work element by element on vectors, producing a logical vector of the same length. That logical vector can then be used directly to filter — placing it inside square brackets keeps only the elements where the condition is TRUE.

Filtering with Comparisons

scores <- c(45, 78, 92, 60, 88)
scores >= 60
scores[scores >= 60]

Common Pitfalls

  • It's easy in some languages to write if (x = 5) by mistake instead of if (x == 5). R protects you here — using = for assignment inside an if() condition's parentheses is a syntax error, catching the typo immediately.
  • Floating-point numbers can fail an == check because of tiny rounding errors — for example 0.1 + 0.2 == 0.3 evaluates to FALSE. Use isTRUE(all.equal(a, b)) when comparing decimals.
  • Any comparison involving NA returns NA rather than TRUE or FALSE — test for missing values with is.na(x) instead of x == NA.

Floating Point and NA

0.1 + 0.2 == 0.3
isTRUE(all.equal(0.1 + 0.2, 0.3))
NA == 5
is.na(NA)
Note: Because NA == anything produces NA, a condition like if (x == NA) never evaluates to TRUE, even when x really is NA. Always check missing values with is.na(x).