R Programming - Find Elements Present in Two Given Data Frames
R Programming: Data frame Exercise-20 with Solution
Write a R program to find elements which are present in two given data frames.
Sample Solution:
R Programming Code:
# Create vector 'a' with elements "a", "b", "c", "d", "e"
a = c("a", "b", "c", "d", "e")
# Create vector 'b' with elements "d", "e", "f", "g"
b = c("d", "e", "f", "g")
# Print a message indicating the original dataframes
print("Original Dataframes")
# Print the contents of vector 'a'
print(a)
# Print the contents of vector 'b'
print(b)
# Print a message indicating the elements present in both dataframes
print("Elements which are present in both dataframe:")
# Find and store elements common to both vectors 'a' and 'b'
result = intersect(a, b)
# Print the elements that are present in both vectors
print(result)
Output:
[1] "Original Dataframes" [1] "a" "b" "c" "d" "e" [1] "d" "e" "f" "g" [1] "Elements which are present in both dataframe:" [1] "d" "e"
Explanation:
- Create Vector 'a':
- a = c("a", "b", "c", "d", "e")
- Defines a vector a containing the elements "a", "b", "c", "d", and "e".
- Create Vector 'b':
- b = c("d", "e", "f", "g")
- Defines a vector b containing the elements "d", "e", "f", and "g".
- Print Original Dataframes Message:
- print("Original Dataframes")
- Prints the message "Original Dataframes" to indicate the start of the output for the vectors.
- Print Vector 'a':
- print(a)
- Displays the contents of vector a.
- Print Vector 'b':
- print(b)
- Displays the contents of vector b.
- Print Common Elements Message:
- print("Elements which are present in both dataframe:")
- Prints the message "Elements which are present in both dataframe:" to indicate the following output will show common elements.
- Find Intersection of Vectors 'a' and 'b':
- result = intersect(a, b)
- Computes the intersection of vectors a and b, which gives the elements common to both vectors, and stores the result in the variable result.
- Print Common Elements:
- print(result)
- Displays the elements that are present in both vectors a and 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 compare two data frames to find the elements in first data frame that are not present in second data frame.
Next: Write a R program to find elements come only once that are common to both given data frames.
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/dataframe/r-programming-data-frame-exercise-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics