【发布时间】:2021-09-22 22:24:20
【问题描述】:
我有一个函数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)
}
现在,用户可以在f2 中为f1 的任意数量的参数提供值,例如:
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
有关如何通过f2 将此类动态参数传递给f1 的任何建议?我看过其他问题,例如 1 和 2,但我认为它们没有解决这个问题。
【问题讨论】:
标签: r function variables dynamic arguments