R: Set Operations (original) (raw)

sets {base} R Documentation

Description

Performs set union, intersection, (asymmetric!) difference, equality and membership on two vectors.

Usage

union(x, y)
intersect(x, y)
setdiff(x, y)
setequal(x, y)

is.element(el, set)

Arguments

x, y, el, set vectors (of the same mode) containing a sequence of items (conceptually) with no duplicated values.

Details

The set operations are intended for “same-kind” “vector-like” objects containing sequences of items. However, being “vector-like” cannot easily be ascertained (in particular as [is.vector](../../base/help/is.vector.html)() enforces a very narrow concept of “vector”).

Thus, for R < 4.5.0, the set operands were always transformed via[as.vector](../../base/help/as.vector.html)() (so that in particular, factors were coerced to character vectors). Starting with R 4.5.0, operands of the “same kind” (in the sense that [isa](../../base/help/isa.html)(x, class(y))or [isa](../../base/help/isa.html)(y, class(x)) which appear to be “vector-like” (in the sense that dim(x) has length at most one, and subscripting x and/ory by 0L leaves the class unchanged) are no longer transformed. In particular, union, intersection and set difference of two factors now give factors (see the examples).

is.element(x, y) is identical to x %in% y (after possibly transforming via [as.vector](../../base/help/as.vector.html)()).

Value

For union, a vector of a common mode or class.

For intersect, a vector of a common mode or class, orNULL if x or y is NULL.

For setdiff, a vector of the same [mode](../../base/help/mode.html) or class as x.

A logical scalar for setequal and a logical of the same length as x for is.element.

See Also

[%in%](../../base/help/+25in+25.html)

plotmath’ for the use of union andintersect in plot annotation.

Examples

(x <- c(sort(sample(1:20, 9)), NA))
(y <- c(sort(sample(3:23, 7)), NA))
union(x, y)
intersect(x, y)
setdiff(x, y)
setdiff(y, x)
setequal(x, y)

## True for all possible x & y :
setequal( union(x, y),
          c(setdiff(x, y), intersect(x, y), setdiff(y, x)))

is.element(x, y) # length 10
is.element(y, x) # length  8

## Factors:
x <- as.factor(c("A", "B", "A"))
y <- as.factor(c("B", "b"))
union(x, y)
intersect(x, y)
setdiff(x, y)
setdiff(y, x)
## (Note that union() and intersect() merge the levels.)

[Package _base_ version 4.6.0 Index]