这有效:
\n\n> match.arg("", choices="")\n[1] ""\nRun Code Online (Sandbox Code Playgroud)\n\n但:
\n\n> match.arg("", choices=c("", "blue"))\nError during wrapup: \'arg\' should be one of \xe2\x80\x9c\xe2\x80\x9d, \xe2\x80\x9cblue\xe2\x80\x9d\nRun Code Online (Sandbox Code Playgroud)\n\n这是一个错误吗?有没有一种简单的方法可以让它发挥作用?
\n\n当然,我可以采取解决方法,例如使用"none"代替"",然后替换,以防这是匹配值。
choices <- c("", "blue")\nchoices[charmatch("", table=choices)]\nRun Code Online (Sandbox Code Playgroud)\n\nNA如果没有匹配值则返回。因此,在这种情况下仍然需要编写错误消息。
好吧,由于没有选项可以处理这种情况,所以我对该函数进行了修改match.arg(感谢@akrun)。
我只是更换了线路
i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)
Run Code Online (Sandbox Code Playgroud)
和
i <- charmatch(arg, choices, nomatch = 0L)
Run Code Online (Sandbox Code Playgroud)
这是修改后的函数(至少它适用于 中给出的示例?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]
}
Run Code Online (Sandbox Code Playgroud)