Apply a function over all combinations of arguments (output as list)

635 views Asked by At

This solution is almost what I need, but do not worked to my case. Here is what I have tried:

comb_apply <- function(f,...){
  exp <- expand.grid(...,stringsAsFactors = FALSE)
  apply(exp,1,function(x) do.call(f,x))
}

#--- Testing Code
l1 <- list("val1","val2")
l2 <- list(2,3)

testFunc<-function(x,y){
  list(x,y)
}

#--- Executing Test Code
comb_apply(testFunc,l1,l2)
comb_apply(paste,l1,l2)

It works for paste example, but I get the message: Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2) when I try my testFunc.

My expectation is to get as result:

list(list("val1",2),list("val1",3),list("val2",2),list("val2",3))

Motivation

I came from Mathematica, on which perform this operation is as simple as:

l1 = {"val1", "val2"}
l2 = {2, 3}
testFunc = {#1, #2} &
Outer[testFunc, l1, l2]

How can I do it in R?

2

There are 2 answers

0
Murta On BEST ANSWER

After some try and error attempts, I found a solution.

In order to make comb_apply to work, I needed to unname each exp value before use it. Here is the code:

comb_apply <- function(f,...){
  exp <- expand.grid(...,stringsAsFactors = FALSE)
  apply(exp,1,function(x) do.call(f,unname(x)))
}

Now, executing str(comb_apply(testFunc,l1,l2)) I get the desired result, without change testFunc.

0
baptiste On

I'd use mapply or plyr::mlply for this,

comb_apply <- function(f,..., MoreArgs=list()){
  exp <- unname(expand.grid(...,stringsAsFactors = FALSE))
  do.call(mapply, c(list(FUN=f, SIMPLIFY=FALSE, MoreArgs=MoreArgs), exp))
}