简体   繁体   English

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

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

Issue:问题:

I want to use a function default_arg() to access the default value of arg in the context of a function func .我想使用 function default_arg()在 function func的上下文中访问arg的默认值。 However, I'd also like this function to be clever enough to guess which function and which argument I want in a couple of cases:但是,我也希望这个 function 足够聪明,能够在某些情况下猜出哪个 function 和我想要的参数:

Case 1 - Used With Explicit Arguments:案例 1 - 与显式 Arguments 一起使用:

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

Case 2 - Used Within a Function Body案例 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
}

Case 3 - Used as a Parameter:案例 3 - 用作参数:

tester_1(
  x = 2,
  y = 1,
  z = default_arg() # This would evaluate to 3
)

Current Approach:当前方法:

I'm able to create something that works in cases 1 and 2, but I'm unsure how to approach Case 3. Here is the approach I'm using currently, using some functions from rlang :我能够创建适用于案例 1 和案例 2 的内容,但我不确定如何处理案例 3。这是我目前使用的方法,使用rlang中的一些函数:

default_arg <- function(arg, func = sys.function(sys.parent())) {
  formals(func)[[as_name(enquo(arg))]]
}

In my proposed solution, I also eliminated the rlang dependency (please see below):在我提出的解决方案中,我还消除了 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

Basically, it is just parsing the call and extracting the relevant information.基本上,它只是解析调用并提取相关信息。 Though this works, I am sure you can still make it neater by avoiding the conditionals.虽然这行得通,但我相信您仍然可以通过避免条件来使它更整洁。 Good luck!祝你好运!

Best, Ventrilocus.最好的,Ventrilocus。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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