Intersection of Two Objects in R Programming – intersect() Function
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
# R program to illustrate # intersection of two vectors # Vector 1 x1 <- c (1, 2, 3, 4, 5, 6, 5, 5) # Vector 2 x2 <- c (2:4) # Intersection of two vectors x3 <- intersect (x1, x2) print (x3) |
Output:
[1] 2 3 4
Example 2: intersect() function with character vectors
R
#define two vectors x <- c ( 'A' , 'B' , 'C' , 'D' , 'E' , 'F' ) y <- c ( 'C' , 'D' , 'E' , 'F' ) #find intersection between two vectors intersect (x, y) |
Output:
[1] "C" "D" "E" "F"
Example 3: The intersection of two data frames
R
# R program to illustrate # the intersection of two data frames # Data frame 1 data_x <- data.frame (x1 = c (2, 3, 4), x2 = c (1, 1, 1)) # Data frame 2 data_y <- data.frame (y1 = c (2, 3, 4), y2 = c (2, 2, 2)) # Intersection of two data frames data_z <- intersect (data_x, data_y) print (data_z) |
Output:
$x1
[1] 2 3 4
Example 4: The intersection of two Matrix
R
# create matrix one a1<- matrix (1:9,3,3) a1 # create matrix secound a2<- matrix (1:12,3,4) a2 # intersect both metrix 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
Contact Us