如何在 R 中的函数内为函数提供动态数量的参数?
How to provide dynamic number of arguments to a function inside a function in R?
我有一个函数 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 and 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
我有一个函数 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 and 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