How to Check if a Value Exists in a Vector in R

· 1 min read · Updated March 14, 2026 · beginner
r vectors data-analysis

Checking if a value exists in a vector is a common task in R.

Using %in%

The simplest approach is the %in% operator:

x <- c("apple", "banana", "cherry")

"banana" %in% x
# [1] TRUE

"grape" %in% x
# [1] FALSE

Check multiple values at once:

c("banana", "grape", "apple") %in% x
# [1]  TRUE FALSE  TRUE

Using match()

match() returns the position or NA if not found:

match("banana", x)
# [1] 2

!is.na(match("grape", x))
# [1] FALSE

Practical examples

Filter data frame 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

Exclude values:

x <- c("a", "b", "c", "d")
x[!x %in% c("b", "d")]
# [1] "a" "c"

See Also