r vector if item is present

R Check whether Specific Item is present in Vector

Posted on

How To Check Whether Specific Item is Present in Vector

To check if specific item is present in a given vector in R language, use %in% operator. This will return TRUE if the item is present, and returns FALSE if specific item is not present.

The Syntax:

item %in% x

Examples:

m <- c("p", "q", "r", "s")
item1 <- "q"
item2 <- "t"

if (item1 %in% m) {
  print("Item is present.")
} else {
  print("Item is not present.")
}

if (item2 %in% m) {
  print("Item is present.")
} else {
  print("Item is not present.")
}

#output:
[1] "Item is present."
[1] "Item is not present."

Conclusion:

We use %in% operator to check if specific item is present in a given vector in R programming.