setdiff()
setdiff(x, y) Returns:
vector · Updated March 13, 2026 · Base Functions sets vectors setdiff base
The setdiff() function returns elements that are in the first vector but not in the second. It performs a set difference operation.
Syntax
setdiff(x, y)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | vector | First input vector |
y | vector | Second input vector |
Examples
Basic usage
x <- c(1, 2, 3, 4, 5)
y <- c(3, 4, 5, 6, 7)
setdiff(x, y)
# [1] 1 2
Character vectors
a <- c("apple", "banana", "cherry")
b <- c("banana", "cherry", "date")
setdiff(a, b)
# [1] "apple"
Order is preserved
x <- c(5, 3, 1, 4, 2)
y <- c(4, 2)
setdiff(x, y)
# [1] 5 3 1
Common Patterns
Finding unique rows in one data frame vs another
df1 <- data.frame(id = 1:5)
df2 <- data.frame(id = 3:7)
ids1 <- df1$id
ids2 <- df2$id
new_ids <- setdiff(ids1, ids2)
df1[df1$id %in% new_ids, ]
# id
# 1 1
# 2 2
Removing handled cases
# All cases minus already processed
all_cases <- 1:100
processed <- c(5, 10, 15, 20)
remaining <- setdiff(all_cases, processed)
length(remaining)
# [1] 96