rho*_*ron 4 arguments r function
举个例子,假设我有一个带有几个可选参数的函数:
result <- function_with_several_optional_arguments(a=1, b=2, c=3)
Run Code Online (Sandbox Code Playgroud)
根据变量foo
,我想提供d=1
或者让它采用默认值,这是我所不知道的.
我可以
if (foo) {
result <- function_with_several_optional_arguments(a=1, b=2, c=3, d=1)
} else {
result <- function_with_several_optional_arguments(a=1, b=2, c=3)
}
Run Code Online (Sandbox Code Playgroud)
但这很快导致了大量的代码重复 - 特别是如果我想有条件地提供许多参数.
我如何有条件地提供参数或保留默认值?
理想情况下,我会做类似的事情
result <- function_with_several_optional_arguments(a=1, b=2, c=3, ifelse(foo, d=1))
Run Code Online (Sandbox Code Playgroud)
但我不知道是否有任何类似的支持.
用途do.call
:
Args <- list(a = 1, b = 2, c = 3)
if (foo) Args$d <- 1
do.call("fun", Args)
Run Code Online (Sandbox Code Playgroud)
第二行也可以写成: Args$d <- if (foo) 1
归档时间: |
|
查看次数: |
210 次 |
最近记录: |