Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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”


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 26 Mar, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials