The Art of R Programming

(WallPaper) #1

8.5 Set Operations.............................................................


R includes some handy set operations, including these:


  • union(x,y): Union of the setsxandy

  • intersect(x,y): Intersection of the setsxandy

  • setdiff(x,y): Set difference betweenxandy, consisting of all elements of
    xthat are not iny

  • setequal(x,y): Test for equality betweenxandy

  • c %in% y: Membership, testing whethercis an element of the sety

  • choose(n,k): Number of possible subsets of sizekchosen 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]12589
> intersect(x,y)
[1]15
> setdiff(x,y)
[1] 2
> setdiff(y,x)
[1]89
> 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 from Section 7.12 that you can write your own binary operations.
For instance, consider coding the symmetric difference between two sets—
that is, all the elements belonging to exactly one of the two operand sets.
Because the symmetric difference between setsxandyconsists exactly of
those elements inxbut notyand vice versa, the code consists of easy calls
tosetdiff()andunion(), as follows:

> symdiff
function(a,b) {
sdfxy <- setdiff(x,y)
sdfyx <- setdiff(y,x)

202 Chapter 8

Free download pdf