Open In App

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

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

Example 1:




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:




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”


Article Tags :