将函数应用于所有参数组合(作为列表输出) [英] 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
示例,但是当我尝试使用testFunc
时收到消息:Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2)
.
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
.
我的期望是得到结果:
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
中做到这一点?
How can I do it in R
?
推荐答案
经过几次尝试和错误尝试后,我找到了解决方案.
After some try and error attempts, I found a solution.
为了使comb_apply
正常工作,我需要在使用每个exp值之前先unname
.这是代码:
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屋!