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

标签 r assertthat

我是 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!
创建于 2020-06-28 由 reprex package (v0.3.0)
但是在使用多个 args 时似乎需要做很多工作。
我看了assetthatcheckmate包,但我不清楚什么是 正确或标准 方法来做到这一点。

最佳答案

我建议使用 allowlistdenylist ,取决于哪个较短(您将有多少异常(exception)),但您必须以某种方式对它们进行硬编码。
例如:

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

关于r - 依赖于其他参数的匹配参数的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62625428/

相关文章:

r - 在 R 中创建事件时间变量

java - 方法 is(int) 未定义

r - 来自assert_that() 的警告而不是错误?

r - R中的igraph - 找到所有可访问的顶点

r - 使用 data.table (R 3.1.1) 进行字符串分组(聚合)

r - 使用 R 创建与 twitter 流 API 的持久连接

r - R中直方图轴上的千位分隔符

java - 如何使 JUnit assertThat() 使用下限通配符?

java - 当 JUnit 5 没有 assertThat() 函数时,如何将 Hamcrest 与 JUnit 5 一起使用?