Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object.
Syntax: setdiff(x, y)
Parameters:
- x and y: Objects with sequence of items
R - setdiff() Function Example
Example 1: Apply setdiff to Numeric Vectors in R Language
# 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)
Output:
[1] 1 5 6
Example 2: Apply setdiff to Character Vectors in R Language
# 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)
Output:
[1] "GEEKS"
Example 3: setdiff Between R Dataframes
# 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)
Output:
x1 1 5 2 6 3 7