R Program to Check if a Vector Contains the Given Element

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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
To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)