gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:52:01 24 4
gpt4 key购买 nike

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 .

关于r - 对所有参数组合应用函数(输出为列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com