Set Operations
R includes some handy set operations, including these:
union(x,y)
: Union of the setsx
andy
intersect(x,y)
: Intersection of the setsx
andy
setdiff(x,y)
: Set difference betweenx
andy
, consisting of all elements ofx
that are not iny
setequal(x,y)
: Test for equality betweenx
andy
c %in% y
: Membership, testing whetherc
is an element of the sety
choose(n,k)
: Number of possible subsets of sizek
chosen from a set of sizen
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.