R Set Operators
R treats ordinary vectors as sets, and functions like union(), intersect(), setdiff(), and %in% let you compare and combine them without writing manual loops.
What Counts as a Set in R
R doesn't have a dedicated "set" data type. Instead, you represent a set as an ordinary vector, and a handful of built-in functions treat that vector's unique values as a mathematical set, automatically ignoring duplicates.
Combining, Overlapping, and Differencing
union() returns every value that appears in either vector, with duplicates removed. intersect() returns only the values present in both vectors. setdiff(x, y) returns the values in x that do not appear in y — note that setdiff() is not symmetric, so setdiff(x, y) and setdiff(y, x) usually give different answers.
Example
fruits_alex <- c("apple", "banana", "cherry")
fruits_bea <- c("banana", "cherry", "date")
union(fruits_alex, fruits_bea)
# "apple" "banana" "cherry" "date"
intersect(fruits_alex, fruits_bea)
# "banana" "cherry"
setdiff(fruits_alex, fruits_bea)
# "apple"Testing Membership with %in%
%in% checks whether each element of one vector appears in another, returning a logical vector the same length as the left-hand side. It's often more useful day to day than a full set operation, especially when you just need a yes/no answer for each item.
Example
"banana" %in% fruits_bea
# TRUE
fruits_alex %in% fruits_bea
# FALSE TRUE TRUERemoving Duplicates with unique()
Since R treats plain vectors as sets, unique() is the function that actually strips out duplicate values — it's what makes union() behave correctly even when the original vectors already contain repeats.
Exercise: R Sets
What does union(x, y) return when x and y share some elements?