5  Logical Operators in R

Logical operators are used to compare values and return TRUE or FALSE. They are very useful in conditions, filtering, and control flow.

5.1 List of commonly used logical operators in R.

== : equal to

!= : not equal to

> : greater than

< : less than

<= : less than or equal to

>= : greater than or equal to

| : OR (at least one condition must be TRUE)

& : AND (both conditions must be TRUE)

Examples

c(1, 2, 3) != c(10, 20, 3)
[1]  TRUE  TRUE FALSE
1:5 > 3
[1] FALSE FALSE FALSE  TRUE  TRUE
1:5 < 3
[1]  TRUE  TRUE FALSE FALSE FALSE

5.2 Membership Operator: %in%

The %in% operator is used to check whether elements of one vector are present in another vector.

Returns a logical vector (TRUE or FALSE) of the same length as the first input.

Example

x <- 1:10 y <- 1:3 x %in% y # Is each element of x in y? y %in% x # Is each element of y in x?