In this article, we will discuss how we do the Intersection of Two Objects in R Programming Language using the intersect() function.
What is the intersect() Function?
intersect() function in R Programming Language is used to find the intersection of two Objects. This function takes two objects like Vectors , Dataframes , etc. as arguments and results in a third object with the common data of both objects.
Syntax: intersect(x, y)
Parameters:x and y: Objects with the sequence of items
Example 1: the intersection of two vectors
R
x1 <- c(1, 2, 3, 4, 5, 6, 5, 5)
x2 <- c(2:4)
x3 <- intersect(x1, x2)
print(x3)
Output:
[1] 2 3 4
Example 2: intersect() function with character vectors
R
x <- c('A', 'B', 'C', 'D', 'E', 'F')
y <- c('C', 'D', 'E', 'F')
intersect(x, y)
Output:
[1] "C" "D" "E" "F"
Example 3: T he intersection of two data frames
R
data_x <- data.frame(x1 = c(2, 3, 4),
x2 = c(1, 1, 1))
data_y <- data.frame(y1 = c(2, 3, 4),
y2 = c(2, 2, 2))
data_z <- intersect(data_x, data_y)
print(data_z)
Output:
$x1
[1] 2 3 4
Example 4: T he intersection of two Matrix
R
a1<- matrix(1:9,3,3)
a1
a2<-matrix(1:12,3,4)
a2
intersect(a1,a2)
Output:
[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 [1] 1 2 3 4 5 6 7 8 9
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 :
24 Nov, 2023
Like Article
Save Article