Skip to content
Related Articles

Related Articles

Improve Article

How to check if a vector contains given value in R ?

  • Last Updated : 05 Apr, 2021

We can check if a vector contains a given value using the %in% operator. For this, we have to create a vector with some values. And we have to read input from the user for what value to be checked. Or we can assign some value to a variable explicitly. Using the %in% operator with the below-given syntax we can find the element we are looking for.

Syntax :

value_to_be_checked %in% vector

The above operation only returns a boolean value that is true or false.

Steps –



  • Create vector
  • Set value to be searched
  • Using the given syntax, search for the element in the vector
  • If found print true
  • Else false

Example 1 :

R




vec1 = c(1,2,3,4,5)
  
a = 1 
  
a %in% vec1

Output :

TRUE

Example 2 :

R




vec1 = c("karthik", "nikhil", "sravan"
  
a = "karthik" 
  
a %in% vec1

Output :

TRUE

Example 3 :

R




vec1 = c("karthik", "nikhil", "sravan"
  
a = "krishna" 
  
a %in% vec1

Output :

FALSE




My Personal Notes arrow_drop_up
Recommended Articles
Page :