This post will explain R functions for set operations, such as union, intersection, set difference, and set equality. These R functions come with the base R package, so you do not have to install additional libraries. These functions are easy to remember and can be applied to R vectors and lists.
union(a,b): Union of the sets a and b
This function generates a new set combining the unique elements from sets.
> x <- c(1,20,3,40,5,60)
> y <- c(10,20,30,40,50,60)
> union(x,y)
[1] 1 20 3 40 5 60 10 30 50
intersect(a,b): Intersection of the sets a and b
This function generates a set comprising the common elements of the sets.
> x <- c(1,20,3,40,5,60)
> y <- c(10,20,30,40,50,60)
> intersect(x,y)
[1] 20 40 60
setdiff(a,b): Set difference between a and b, consisting of all elements of a that are not in b
> x <- c(1,20,3,40,5,60)
> y <- c(10,20,30,40,50,60)
> setdiff(x,y)
[1] 1 3 5
setequal(a,b): Test for equality between a and b
> x <- c(1,20,3,40,5,60)
> y <- c(10,20,30,40,50,60)
> setequal(x,y)
[1] FALSE
To apply these functions to R lists, you need to just create lists: x and y
Please let me know in the comments if you have any questions.