Applying a function to all combinations of arguments (list output)
This solution is what I need, but doesn't work in my case. Here's what I've 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 the example paste
, but I get the message: Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2)
when I try to execute testFunc
.
My expectation is to get the result:
list(list("val1",2),list("val1",3),list("val2",2),list("val2",3))
Motivation
I came from Mathematica , which is as simple as doing this operation:
l1 = {"val1", "val2"}
l2 = {2, 3}
testFunc = {#1, #2} &
Outer[testFunc, l1, l2]
How to do it in R
?
source to share
After some try and try and error, I found a solution.
To make it work comb_apply
I needed unname
every exp value before using 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, by executing str(comb_apply(testFunc,l1,l2))
, I get the desired output unchanged testFunc
.
source to share
Since it works with paste
, one way is to replace the explicit arguments with ...
inside testFunc
.
testFunc<-function(...){
ll <- list(...) ## this is best way to deal with ... arguments!
## see match.call for example
list(ll[[1]],ll[[2]])
}
You can check it:
dput(comb_apply(testFunc,l1,l2))
list(list("val1", 2), list("val2", 2), list("val1", 3), list("val2", 3))
source to share