Find elements of a Vector not in another Vector in R
R Programming: Vector Exercise-19 with Solution
Write a R program to find the elements of a given vector that are not in another given vector.
Sample Solution :
R Programming Code :
# Define the first vector
a = c(0, 10, 10, 10, 20, 30, 40, 40, 40, 50, 60)
# Define the second vector
b = c(10, 10, 20, 30, 40, 40, 50)
# Print the first vector
print("Original vector-1:")
print(a)
# Print the second vector
print("Original vector-2:")
print(b)
# Find elements in the first vector that are not in the second vector
print("Elements of a that are not in b:")
result = setdiff(a, b)
# Print the result
print(result)
Output:
[1] "Original vector-1:" [1] 0 10 10 10 20 30 40 40 40 50 60 [1] "Original vector-2:" [1] 10 10 20 30 40 40 50 [1] "Elements of a that are not in b:" [1] 0 60
Explanation:
- The code starts by defining two vectors a and b with specific elements. Vector a includes elements such as 0, 10, 20, 30, 40, 50, and 60, while vector b includes elements like 10, 20, 30, 40, and 50.
- It then prints "Original vector-1:" followed by the elements of vector a.
- Similarly, it prints "Original vector-2:" followed by the elements of vector b.
- The code proceeds to find the elements in vector a that are not present in vector b using the setdiff() function.
- Finally, it prints "Elements of a that are not in b:" followed by the result, which shows the unique elements in a that do not appear in b.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to list the distinct values in a vector from a given vector.
Next: Write a R program to reverse the order of given vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-19.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics