【问题标题】:How can I access the default value of a function argument?如何访问函数参数的默认值?
【发布时间】: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


    【解决方案1】:

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

    基本上,它只是解析调用并提取相关信息。 虽然这可行,但我相信您仍然可以通过避免使用条件来使其更整洁。祝你好运!

    最好, 脑室。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 2011-02-20
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      相关资源
      最近更新 更多