对所有参数组合应用函数(输出为列表) [英] Apply a function over all combinations of arguments (output as list)
问题描述
这个解决方案几乎是我所需要的,但不适用于我的情况.这是我尝试过的:
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)
它适用于 paste
示例,但我收到消息:Error in (function (x, y) : used arguments (Var1 = "val1", Var2 = 2)
当我尝试我的 testFunc
时.
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))
动机
我来自Mathematica,在它上面执行这个操作很简单:
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]
如何在 R
中实现?
推荐答案
经过一些尝试和错误尝试,我找到了解决方案.
After some try and error attempts, I found a solution.
为了使 comb_apply
工作,我需要在使用它之前 unname
每个 exp 值.代码如下:
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)))
}
现在,执行 str(comb_apply(testFunc,l1,l2))
我得到了想要的结果,无需更改 testFunc
.
Now, executing str(comb_apply(testFunc,l1,l2))
I get the desired result, without change testFunc
.
这篇关于对所有参数组合应用函数(输出为列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!