对参数的所有组合应用函数(输出为列表)

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

This solution 几乎是我所需要的,但对我的情况不起作用。 这是我尝试过的:

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)

它适用于 paste 示例,但我收到消息:Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2) 当我尝试我的 testFunc.

我的期望是得到结果:

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

动机

我来自Mathematica,在上面执行这个操作很简单:

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

如何在 R 中完成?

经过反复尝试,我找到了解决方案。

为了让comb_apply工作,我需要在使用前unname每个exp值。这是代码:

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

现在,执行 str(comb_apply(testFunc,l1,l2)) 我得到了想要的结果,没有改变 testFunc

我会使用 mapplyplyr::mlply

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