Set Operations

R includes some handy set operations, including these:

  • union(x,y): Union of the sets x and y

  • intersect(x,y): Intersection of the sets x and y

  • setdiff(x,y): Set difference between x and y, consisting of all elements of x that are not in y

  • setequal(x,y): Test for equality between x and y

  • c %in% y: Membership, testing whether c is an element of the set y

  • choose(n,k): Number of possible subsets of size k chosen from a set of size n

Here are some simple examples of using these functions:

> x <- c(1,2,5)
> y <- c(5,1,8,9)
> union(x,y)
[1] 1 2 5 8 9
> intersect(x,y)
[1] 1 5
> setdiff(x,y)
[1] 2
> setdiff(y,x)
[1] 8 9
> setequal(x,y)
[1] FALSE
> setequal(x,c(1,2,5))
[1] TRUE
> 2 %in% x
[1] TRUE
> 2 %in% y
[1] FALSE
> choose(5,2)
[1] 10

Recall ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.