r - 空字符串的 match.arg 失败

标签 r

这有效:

> match.arg("", choices="")
[1] ""

但:
> match.arg("", choices=c("", "blue"))
Error during wrapup: 'arg' should be one of “”, “blue”

这是一个错误吗?有没有简单的方法让它工作?

当然我可以做一个解决方法,比如使用 "none"而不是 ""然后替换,以防这是匹配值。

编辑:一个可能但不完美的解决方法
choices <- c("", "blue")
choices[charmatch("", table=choices)]

这将返回 NA如果没有匹配的值。因此,在这种情况下仍然需要对错误消息进行编码。

最佳答案

好吧,既然没有办法处理这种情况,我对 match.arg 做了一个修改。函数(感谢@akrun)。

我只是更换了线路

i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)


i <- charmatch(arg, choices, nomatch = 0L)

这是修改后的函数(至少它适用于 ?match.arg 中给出的示例):
match.arg2 <- function(arg, choices, several.ok=FALSE){
  if (missing(choices)) {
    formal.args <- formals(sys.function(sys.parent()))
    choices <- eval(formal.args[[as.character(substitute(arg))]])
  }
  if (is.null(arg)) 
    return(choices[1L])
  else if (!is.character(arg)) 
    stop("'arg' must be NULL or a character vector")
  if (!several.ok) {
    if (identical(arg, choices)) 
      return(arg[1L])
    if (length(arg) > 1L) 
      stop("'arg' must be of length 1")
  }
  else if (length(arg) == 0L) 
    stop("'arg' must be of length >= 1")
  i <- charmatch(arg, choices, nomatch = 0L)
  if (all(i == 0L)) 
    stop(gettextf("'arg' should be one of %s", paste(dQuote(choices), 
                                                     collapse = ", ")), domain = NA)
  i <- i[i > 0L]
  if (!several.ok && length(i) > 1) 
    stop("there is more than one match in 'match.arg'")
  choices[i]
}

关于r - 空字符串的 match.arg 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41441170/

相关文章:

r - 使用 R,如何在数据帧的单列中标记连续的重复值

r - R 中的函数和 try()

python - R lm 与 Python sklearn linear_model

r - $R_LIBS_USER下如何快速复制/更新本地库?

r - 如何在 geom_spoke 上获取图例

R-Package tmap/protolite 安装失败 :

r - 如何在 R 中构建 GA 的变异算法

r - 如何在 blogdown 中向网页选项卡添加图标

r - 如何在保持字母顺序的情况下输出图形

R sum 包含 NaN 的矩阵列表