3

我是 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 包(v0.3.0)于 2020 年 6 月 28 日创建

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

我看了看assetthatcheckmate包装,但我不清楚什么是正确或标准的方法。

4

1 回答 1

3

我建议使用allowlistor denylist,具体取决于哪个更短(您将有多少例外),但您必须以某种方式对它们进行硬编码。

例如:

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% ...)。

于 2020-06-28T16:54:37.360 回答