rsetset-operations

Set operations on list of sets in R using sets package


I am using sets package in R. Now, i have a list of sets and I want to perform set operations on the list without having to loop. Like, I can do set_intersection with a variable number of arguments

set_intersection(set(1,2), set(2,3), set(4,5), set(5,6)..)

But what if I have a list like

ls = list(set(1,2), set(2,3), set(4,5), set(5,6))

How do I take intersection of all sets contained in ls? Tried to google it but can't find much.


Solution

  • We can use Reduce with set_intersection

    library(sets)
    Reduce(set_intersection, ls)
    

    or with do.call

    do.call(set_intersection, ls)
    

    NOTE: It is better not to name objects with function names (ls is a function)