繁体   English   中英

如何访问 function 参数的默认值?

[英]How can I access the default value of a function argument?

问题:

我想使用 function default_arg()在 function func的上下文中访问arg的默认值。 但是,我也希望这个 function 足够聪明,能够在某些情况下猜出哪个 function 和我想要的参数:

案例 1 - 与显式 Arguments 一起使用:

tester_1 <- function(x = 1, y = 2, z = 3) {
  x * y + z
}
default_arg(x, tester_1) # this would evaluate to 1

案例 2 - 在 Function 体内使用

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))]]
}

在我提出的解决方案中,我还消除了 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM