我有一个功能 f1
执行一些任务。假设它执行以下任务:
f1 = function(a=1,b=1,c=2){
res = (a+b)*c
return(res)
}
现在,这个函数是通过另一个函数调用的,f2
.此函数可以获取参数的动态数量,创建所有可能的组合并将值提供给函数 f1
如下:f2 = function(...){
arglist = list(...)
df = expand.grid(arglist) # Create all possible combinations of the given argument list.
out = apply(df,1,function(x) f1(x))
res = unlist(out)
return(res)
}
现在,用户可以为 f1
的任意数量的参数提供值。在 f2
喜欢:f2(a=10)
# Output: 22
但是,如果我尝试任何其他场景,我不会得到理想的结果:f2(c=10)
# f2 Output: 22
# Target Output: 20
f2(a=5, c=c(5,10))
# f2 Output:
12 12
12 22
# Target Output: 30 60
关于如何将此类动态参数传递给 f1
的任何建议通过 f2
?.我看过其他问题,如 1和 2但我认为他们没有解决这个问题。
最佳答案
如果更改 apply
至 do.call
,它会按预期工作。请注意 apply
与 MARGIN = 2
, 分别循环遍历 'df' 的列,而 'f1' 需要所有可用列的值(或使用默认值)来计算( (a + b) * c
)
f2 <- function(...){
arglist = list(...)
df = expand.grid(arglist)
do.call(f1, df)
}
和 f1
f1 <- function(a=1,b=1,c=2){
(a+b)*c
}
-测试> f2(a = 10)
[1] 22
> f2(c = 10)
[1] 20
> f2(a = 5, c= c(5, 10))
[1] 30 60
关于r - 如何为R中的函数内的函数提供动态数量的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68369618/