R编程中两个对象的交集——intersect()函数
R 语言中的intersect()
函数用于查找两个对象的交集。此函数将向量、数据帧等两个对象作为参数,并生成第三个对象,其中包含两个对象的公共数据。
Syntax: intersect(x, y)
Parameters:
x and y: Objects with sequence of items
示例 1:
# 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)
输出:
[1] 2 3 4
示例 2:
# 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)
输出:
y1
1 2
2 3
3 4