[英]How can I access the default value of a function argument?
我想使用 function default_arg()
在 function func
的上下文中訪問arg
的默認值。 但是,我也希望這個 function 足夠聰明,能夠在某些情況下猜出哪個 function 和我想要的參數:
tester_1 <- function(x = 1, y = 2, z = 3) {
x * y + z
}
default_arg(x, tester_1) # this would evaluate to 1
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
}
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))]]
}
在我提出的解決方案中,我還消除了 rlang 依賴項(請參見下文):
default_arg <- function(arg = NULL, func = NULL) {
if(deparse(substitute(arg)) == "NULL" & is.null(func))
{
arg = sys.calls()[[1]]
val = as.character(arg); names(val) = names(arg)
func = val[1]
variable = names(which(val == "default_arg()"))
return(formals(func)[[variable]])
}
if(is.null(func))
{
func = as.character(sys.call(sys.parent()))[1]
}
return(formals(func)[[deparse(substitute(arg))]])
}
default_arg(x, tester_1) # 1
default_arg(y, tester_1) # 2
default_arg(z, tester_1) # 3
tester_2() # 5
tester_1(x = 1, y = 2, z = default_arg()) # 5
tester_1(x = 1, y = default_arg(), z = 3) # 5
tester_1(x = default_arg(), y = 2, z = 3) # 5
基本上,它只是解析調用並提取相關信息。 雖然這行得通,但我相信您仍然可以通過避免條件來使它更整潔。 祝你好運!
最好的,Ventrilocus。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.