# sets

##### Set Operations

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

- Keywords
- misc

##### 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

Each of `union`

, `intersect`

, `setdiff`

and
`setequal`

will discard any duplicated values in the arguments,
and they apply `as.vector`

to their arguments (and so
in particular coerce factors to character vectors).

`is.element(x, y)`

is identical to `x %in% y`

.

##### Value

A vector of the same `mode`

as `x`

or `y`

for
`setdiff`

and `intersect`

, respectively, and
of a common mode for `union`

.

A logical scalar for `setequal`

and a logical of the same
length as `x`

for `is.element`

.

##### See Also

‘plotmath’ for the use of `union`

and
`intersect`

in plot annotation.

##### Examples

`library(base)`

```
# NOT RUN {
(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
# }
```

*Documentation reproduced from package base, version 3.6.2, License: Part of R 3.6.2*

### Community examples

**mark@niemannross.com**at Nov 15, 2018 base v3.5.1

example for [LinkedIn Learning Video](https://linkedin-learning.pxf.io/rweekly_equalIn) ```r # create two vectors to demonstrate vectA <- c(1:10) vectB <- c(10:15) # is vectA == vectB ? setequal(vectA, vectB) # what parts of vectA are in vectB? is.element(vectA, vectB) # what parts of vectB are in vectA? is.element(vectB, vectA) # equivalent notation for is.element(vectA, vectB) vectA %in% vectB # elements in sets do not need to be sorted vectBRandom <- sample(vectB, length(vectB)) vectBRandom intersect(vectA, vectBRandom) setdiff(vectBRandom, vectA) setequal(vectB, vectBRandom) ```

**mark@niemannross.com**at Nov 5, 2018 base v3.5.1

Example files from [LinkedIn Learning, R for Data Science, Lunchbreak Lessons](https://linkedin-learning.pxf.io/Rweekly_setsUnionInterDiff). ```r # create two vectors to demonstrate vectA <- c(1:10) vectB <- c(10:15) # union - combine the vectors - removing duplicates union(vectA, vectB) # intersect - find the overlap intersect(vectA, vectB) # what is unique about vectA? setdiff(vectA, vectB) # what is unique about vectB? setdiff(vectB, vectA) # elements in sets do not need to be sorted vectBRandom <- sample(vectB, length(vectB)) vectBRandom intersect(vectA, vectBRandom) setdiff(vectBRandom, vectA) setequal(vectB, vectBRandom) ```