28  Set Operations

R includes set operations that can be used on vectors of any type. It does not include a dedicated set class. The inputs to set operations should be of the same mode.

x <- c("a", "b", "c", "d")
y <- c("c", "d", "e", "f")

28.1 Set Union

union(x, y)
[1] "a" "b" "c" "d" "e" "f"

28.2 Set Intersection

intersect(x, y)
[1] "c" "d"

28.3 Set difference

R’s setdiff() returns the asymmetric set difference between two vectors.

setdiff(x, y) will return elements in x not present in y:

setdiff(x, y)
[1] "a" "b"
setdiff(y, x)
[1] "e" "f"

28.4 Test set equality

setequal(x, y)
[1] FALSE
setequal(c(1, 3, 5), c(3, 5, 1))
[1] TRUE

28.5 Test if a value is element of a set

is.element("b", x)
[1] TRUE

is the same as:

"b" %in% x
[1] TRUE