这有效:
> 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/