依赖于其他参数的匹配参数的最佳实践

Best practice for match arguments that depends on others

我是 R 函数的新手,到目前为止我会检查如下参数:

foo = function(state = c("solid", "liquid"),
               thing = c("rock", "water")) {
  
  state = match.arg(state)
  thing = match.arg(thing)
  
  if (state == "solid" & thing == "water") {
    stop("thing can't be water if state is solid!")
  }
  
  if (state == "liquid" & thing == "rock") {
    stop("thing can't be rock if state is liquid!")
  }
  
}

foo("solid", "brick")
#> Error in match.arg(thing): 'arg' deve ser um dentre "rock", "water"

foo("solid", "water")
#> Error in foo("solid", "water"): thing can't be water if state is solid!

foo("liquid", "rock")
#> Error in foo("liquid", "rock"): thing can't be rock if state is liquid!

reprex package (v0.3.0)

于 2020 年 6 月 28 日创建

但是在使用多个参数时似乎需要做很多工作。

我查看了 assetthatcheckmate 软件包,但我不清楚 正确或标准 方法是什么.

我建议 allowlistdenylist,具体取决于哪一个更短(你会有多少 exceptions),但是你'我必须以某种方式对它们进行硬编码。

例如:

foo = function(state = c("solid", "liquid", "both"),
               thing = c("rock", "brick", "water", "either")) {
  
  state = match.arg(state)
  thing = match.arg(thing)

  state_denylist <- list(
    solid = "water",
    liquid = c("rock", "brick")
  )

  if (thing %in% state_denylist[[state]]) {
    stop("thing cannot be ", sQuote(thing), " if state is ", sQuote(state))
  }
 
}

或者,如果更容易定义 允许的 组合,那么也许 state_allowlist 并相应地更改您的逻辑 (... && ! thing %in% ...)。