R Program to Check if a Vector Contains the Given Element

Here we will be using the

  • %in% operator
  • match() function
  • any() function.

Example 1: Check if Element Exists in R Vector Using %in%

# create two strings
vowel_letters <- c("a", "e", "i", "o", "u")
 
"a" %in% vowel_letters # TRUE

"s" %in% vowel_letters # FALSE

Output

[1] TRUE
[2] FALSE

In the above example, we have used the %in% operator to check if an element exists in the vector named vowel_letters.

Here,

  1. "a" is present in vowel_letters, so the method returns TRUE
  2. "s" is not present in vowel_letters, so the method returns FALSE

Example 2: Check if Element Exists in R Vector Using match()

The match() function returns a vector position of the element if the element exists. Else the function returns NA. For example,

# create two strings
vowel_letters <- c("a", "e", "i", "o", "u")

# check if "i" is present in vowel_letters
match("i", vowel_letters) # 3

# check if "p" is present in vowel_letters
match("p", vowel_letters) # NA

Output

[1] 3
[1] NA

In the above example, we have used the match() function to check if an element exists in the vector named vowel_letters.

Here,

  1. "i" is present in vowel_letters, so the method returns vector position of element i.e. 3
  2. "p" is not present in vowel_letters, so the method returns NA

Example 3: Check if Element Exists in R Vector Using any()

# create two strings
languages <- c("R", "Swift", "Java", "Python")

# check if "Swift" is present in languages using any()
any("Swift" == languages) # TRUE

# check if "C" is present in languages using any()
any("C" == languages) # FALSE

Output

[1] TRUE
[2] FALSE

Here, we have used the any() function to check if an element exists in the vector named languages.

Since

  1. "Swift" is present in languages, so the method returns TRUE
  2. "C" is not present in languages, so the method returns FALSE

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges