Home > Software design >  Pairwise mapply of two lists in R
Pairwise mapply of two lists in R

Time:10-27

If I want to sum over pairs of two lists, is there an easy way I can do this in R? I tried

mapply(function(x,y) x y, list(1,2,3),list(1,2,3))

but this only gives x[n] y[n] for all n=1..N but I want x[n] y[m] for all m=1..M, n=1..N returned as a list.

Notice I don't want solution to this simple example. I need a general solution that works for non-numeric input as well. The thing I'm trying to do is like:

mapply(function(set_1, set_2) intersect(set_1, set_2), list_of_sets_1, list_of_sets_2)

CodePudding user response:

You may use outer -

values <- c(1, 2, 3)
outer(values, values, ` `)

#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

outer also works for non-numeric input. If the function that you want to apply is not vectorised you can use Vectorize. Since OP did not provide an example I have created one of my own.

list_of_sets_1 <- list(c('a', 'b', 'c'), c('a'))
list_of_sets_2 <- list(c('a', 'c'), c('a', 'b'))

fun <- function(x, y) intersect(x, y)
result <- outer(list_of_sets_1, list_of_sets_2, Vectorize(fun))
result
  • Related