[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.
              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,
- "a"is present in vowel_letters, so the method returns- TRUE
- "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,
- "i"is present in vowel_letters, so the method returns vector position of element i.e. 3
- "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
- "Swift"is present in languages, so the method returns- TRUE
- "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.
