R Language Set operations Set operators for pairs of vectors


Example

Comparing sets

In R, a vector may contain duplicated elements:

v = "A"
w = c("A", "A")

However, a set contains only one copy of each element. R treats a vector like a set by taking only its distinct elements, so the two vectors above are regarded as the same:

setequal(v, w)
# TRUE

Combining sets

The key functions have natural names:

x = c(1, 2, 3)
y = c(2, 4)

union(x, y)
# 1 2 3 4

intersect(x, y)
# 2

setdiff(x, y)
# 1 3

These are all documented on the same page, ?union.