Skip to content
Related Articles

Related Articles

Improve Article

Find the elements of a vector that are not in another vector in R

  • Last Updated : 26 Mar, 2021

Two vectors can hold some values common. This article discusses how can we find set difference of these vectors i.e. display elements which are present in one vector but not in the other.

If we want all the elements of a vector that are not in another vector then we can use setdiff() method in R. It takes two vectors and returns a new vector with the elements of the first vector that are not present in the second vector.

Syntax:

setdiff(a, b)

Approach



  • Create first vector
  • Create second vector
  • Find set difference
  • Store this in another vector
  • Display result

Example 1:

R




a = c(1, 3, 8, 29, 9, 71, 90)
b = c(17, 8, 6, 90)
  
print("vector a is")
  
print("vector b is")
  
print("Elements of vector a that are not in vector b are:")
  
ans = setdiff(a, b)
print(ans)

Output:

[1]  1  3 29  9 71

Example 2:

R




a = c("ram", "rahul", "rohan", "ashish", "rohit", "kapil")
b = c("ram", "aakash", "ashish")
  
print("vector a is")
  
print("vector b is")
  
print("Elements of vector a that are not in vector b are:")
  
ans = setdiff(a, b)
print(ans)

Output:

[1] “rahul” “rohan” “rohit” “kapil”




My Personal Notes arrow_drop_up
Recommended Articles
Page :