setdiff() Function in detail
The setdiff() function in R is used to find elements that are present in the first object but not in the second object.
Syntax:
setdiff(x, y)
Parameters:
xandy: Objects containing a sequence of items.
Example 1: Using setdiff() with Numeric Vectors
# R program to illustrate setdiff() function
# Vector 1
num_vec1 <- c(10, 20, 30, 40, 50, 60, 50, 50)
# Vector 2
num_vec2 <- c(20:40)
# Calling setdiff() function
result <- setdiff(num_vec1, num_vec2)
print(result)
Output:
[1] 10 50 60
Example 2: Using setdiff() with Character Vectors
# R program to illustrate setdiff() function
# Vector 1
char_vec1 <- c("Apple", "Orange")
# Vector 2
char_vec2 <- c("Apple", "Banana", "Mango")
# Calling setdiff() function
result <- setdiff(char_vec1, char_vec2)
print(result)
Output:
[1] "Orange"
Example 3: Using setdiff() with Data Frames
# R program to illustrate setdiff() function
# Data frame 1
df1 <- data.frame(A = c(15, 25, 35),
B = c(5, 5, 5))
# Data frame 2
df2 <- data.frame(C = c(5, 10, 15),
D = c(5, 5, 5))
# Calling setdiff() function
result <- setdiff(df1, df2)
print(result)
Output:
A
1 15
2 25
3 35
Leave a Reply