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
?
After some try and error attempts, I found a solution.
In order to make
comb_apply
to work, I needed tounname
each exp value before use it. Here is the code:Now, executing
str(comb_apply(testFunc,l1,l2))
I get the desired result, without changetestFunc
.