在 R 编程中获取两个对象之间的独占元素 – setdiff()函数
R 编程语言中的setdiff()函数用于查找在第一个对象中但不在第二个对象中的元素。
Syntax: setdiff(x, y)
Parameters:
- x and y: Objects with sequence of items
R – setdiff()函数示例
示例 1:将 setdiff 应用于 R 语言中的数值向量
R
# R program to illustrate
# the use of setdiff() function
# Vector 1
x1 <- c(1, 2, 3, 4, 5, 6, 5, 5)
# Vector 2
x2 <- c(2:4)
# Calling setdiff() Function
x3 <- setdiff(x1, x2)
print(x3)
R
# R program to illustrate
# the use of setdiff() function
# Vector 1
x <- c("GFG", "GEEKS")
# Vector 2
y <- c("GFG", "Welcome", "HOME")
# Calling setdiff() Function
x3 <- setdiff(x, y)
print(x3)
R
# R program to illustrate
# the use of setdiff() function
# Data frame 1
data_x <- data.frame(x1 = c(5, 6, 7),
x2 = c(2, 2, 2))
# Data frame 2
data_y <- data.frame(y1 = c(2, 3, 4),
y2 = c(2, 2, 2))
# Calling setdiff() Function
data_z <- setdiff(data_x, data_y)
print(data_z)
输出:
[1] 1 5 6
示例 2:将 setdiff 应用于 R 语言中的字符向量
R
# R program to illustrate
# the use of setdiff() function
# Vector 1
x <- c("GFG", "GEEKS")
# Vector 2
y <- c("GFG", "Welcome", "HOME")
# Calling setdiff() Function
x3 <- setdiff(x, y)
print(x3)
输出:
[1] "GEEKS"
示例 3:R 数据帧之间的 setdiff
R
# R program to illustrate
# the use of setdiff() function
# Data frame 1
data_x <- data.frame(x1 = c(5, 6, 7),
x2 = c(2, 2, 2))
# Data frame 2
data_y <- data.frame(y1 = c(2, 3, 4),
y2 = c(2, 2, 2))
# Calling setdiff() Function
data_z <- setdiff(data_x, data_y)
print(data_z)
输出:
x1
1 5
2 6
3 7