Set operations on more than two sets in R
[This article was first published on Odd Hypothesis, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Problem
Set operations are a common place thing to do in R, and the enabling functions in the base stats package are:- intersect(x, y)
- union(x, y)
- setdiff(x, y)
- setequal(x, y)
Googling around I found that you can apply set operations to multiple (>2) sets using the Reduce() function. For example, an intersection of sets stored in the list x would be achieved with:
Reduce(intersect, x)
However, things get trickier if you want to do a setdiff() in this manner – that is find the elements that are only in set a, but not in sets b, c, d, …, etc. Since I’m not a master at set theory, I decided to write my own, brute force method to get intersections, unions, and setdiffs for an arbitrary number of sets.
Implementation
The function I wrote uses a truth table to do this where:- rows are the union of all elements in all sets
- columns are sets
To find an element that intersects all sets, the values across the row need to be all TRUE.
To find an element that is only in one set, only one row value is TRUE. To determine which set that element is in, numeric values are applied to each column such that:
- col1 = 1
- col2 = 2
- col3 = 4
- col4 = 8
- … and so on
For example, if an element is only in set 2 (that is column 2) the corresponding row inclusion value is 2. If an element is in both sets 2 and 3 (columns 2 and 3) the corresponding row inclusion value is 6.
Visually …
1 | 2 | 4 | ||
set: | x | y | z | inc.val |
a | T | F | F | 1 |
b | F | T | T | 6 |
c | T | F | T | 5 |
d | T | T | T | 7 |
Thus, determining intersections or setdiffs becomes a simple matter of filtering by row sums.
Code
To leave a comment for the author, please follow the link and comment on their blog: Odd Hypothesis.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.