user3032689 user3032689 - 9 days ago 11
R Question

mapply multiple undefined arguments

Assume you have an undefined nr of lists as possible arguments for a function, for example the following 3 can be picked (this example is as simple as possible, so vectors are stored in lists):

a <- list(c(1,2,3,4,5))
b <- list(c(3,6,7,2,1))
c <- list(c(3,9,8))


If I want to calculate the intersection of all three lists, this can be done as follows:

Map(intersect,c,Map(intersect,a,b))
# or equivalent:
mapply(intersect,c,mapply(intersect,a,b,SIMPLIFY=F))
# [1] 3


But how can I change the nr of arguments to be undefined? I read about
...
, but I cannot get it to work. First idea was to write a function, that can have multiple list arguments defined by
...
:

intersectio <- function(...){
Map(function(...){
intersect(...)
})
}


Q: But that doesn't work of course, because intersect must be applied recursively. Is there any way to achieve this in R?

Q2: Here is an updated example with a nested list structure. How can it be done in this case, i.e. intersect every sublist of the parent list with the associated sublist (same index) of the other parent lists?

a <- list(list(c(1,2,3,4,5)),list(c(3,6,7,2,1)),list(c(3,9,8)))
b <- list(list(c(1,2)),list(c(3,6,9,11,12)),list(c(3)))
c <- list(list(c(1,9)),list(c(65,23,12)),list(c(14,15)))

Answer

As @Roland suggested, you can use Reduce to solve your problem. In the case of flat lists (as in the first version of the question), you can use the following:

Reduce(intersect, c(a, b, c))

In the case of nested lists (as in the updated question), you can just have to wrap that inside a mapply call:

mapply(function(...) Reduce(intersect, c(...)), a, b, c)