【发布时间】:2020-07-29 09:23:56
【问题描述】:
问题:
我想使用函数default_arg() 在函数func 的上下文中访问arg 的默认值。但是,我还希望这个函数足够聪明,可以在几种情况下猜测我想要哪个函数和哪个参数:
案例 1 - 与显式参数一起使用:
tester_1 <- function(x = 1, y = 2, z = 3) {
x * y + z
}
default_arg(x, tester_1) # this would evaluate to 1
案例 2 - 在函数体中使用
tester_2 <- function(x = 1, y = 2, z = 3) {
x_default <- default_arg(x) # this would evaluate to 1
if(x < x_default) {
stop(paste("x should be greater or equal to default value:", x_default))
}
x * y + z
}
案例 3 - 用作参数:
tester_1(
x = 2,
y = 1,
z = default_arg() # This would evaluate to 3
)
目前的方法:
我能够创建适用于案例 1 和 2 的东西,但我不确定如何处理案例 3。这是我目前使用的方法,使用来自 rlang 的一些函数:
default_arg <- function(arg, func = sys.function(sys.parent())) {
formals(func)[[as_name(enquo(arg))]]
}
【问题讨论】:
标签: r function arguments evaluation