How to Check Value Membership in R Vectors
Check value membership in a vector with the %in% operator — the simplest way to test whether a value, or a batch of values, appears in a target set. %in% returns a logical vector the same length as the left-hand side, so it slots directly into subsetting brackets and filter expressions without extra steps. Under the hood it uses a hash set lookup, which means checking many values against a large reference table stays fast even when the table has thousands of entries. This makes %in% the go-to operator for filtering rows by a list of allowed categories, excluding unwanted entries, or validating input against a known set of codes.
x <- c("apple", "banana", "cherry")
"banana" %in% x
# [1] TRUE
c("banana", "grape", "apple") %in% x
# [1] TRUE FALSE TRUE
%in% is implemented as a hash set lookup: O(table size) for setup, then O(1) per lookup. For checking many values against a large table, this is far faster than looping or using any(x == table).
The most common use case is filtering data frames by membership:
df <- data.frame(fruit = c("apple", "banana", "cherry"), price = c(1, 2, 3))
wanted <- c("banana", "cherry")
df[df$fruit %in% wanted, ]
# fruit price
# 2 banana 2
# 3 cherry 3
To exclude values, negate the condition with !:
x <- c("a", "b", "c", "d")
x[!x %in% c("b", "d")]
# [1] "a" "c"
If you need the index position rather than a logical vector, match() returns the position of the first match or NA when the value is absent. Use all(x %in% y) to check that every element of x appears in y.
See also
- match(), Find element positions
- unique(), Extract unique values
- duplicated(), Find duplicates