在定义中使用省略号时,如何在R函数调用中捕获错误或未定义的参数

我正在努力解决一个被承认但我尚未找到一个简单解决方案的问题:当函数定义包含省略号或三个点时,如何捕获传递给R函数的错误指定的参数….

正如Wickham的高级R所述:

Using ... comes at a price — any misspelled arguments will not raise
an error, and any arguments after ... must be fully named. This makes
it easy for typos to go unnoticed.

这是一个例子:

myfun <- function(x, ...) 
    UseMethod("myfun")

myfun.character <- function(x, toLower = FALSE, ...)
    cat("Sent and transformed by myfun:", ifelse(toLower, tolower(x), x), "\n")

myfun("Test String with CaPiTaLs.")
## Sent and transformed by myfun: Test String with CaPiTaLs.
myfun("Test String with CaPiTaLs.", toLower = TRUE)
## Sent and transformed by myfun: test string with capitals. 
myfun("Test String with CaPiTaLs.", tolower = TRUE)
## Sent and transformed by myfun: Test String with CaPiTaLs.
myfun("Test String with CaPiTaLs.", toLower = TRUE, notDefined = 1)
## Sent and transformed by myfun: test string with capitals. 

在这里,toLower的微妙拼写错误导致没有可见的错误,除非输出的失败是小写的,正如用户可能期望的那样.在最后一个例子中,用户认为可以起作用的参数不是,但由于….的性质,它们只是消失在以太中.

当然,我可以通过列表(…)检查…的内容,但我想知道是否有更好的方法,链接到函数中定义的形式或传递的那些.

顺便说一下,有谁知道我们应该叫什么……?我几乎可以肯定我在Julia文档中看到了一个带有名字的引用,但现在找不到了!

添加:

理想情况下,如果参数不是应该在省略号中传递的,当被调用函数范围内的某些内容通过省略号传递给辅助参数时,我想找出生成错误的最佳方法.例如,如何最好地捕获这些错误:

myfun2 <- function(x, ...) 
    UseMethod("my fun")

myfun2.character <- function(x, toLower = FALSE, ...)
    cat("Sent and transformed by myfun:", ifelse(toLower, tolower(x), x), "\n", ...)

myfun2("Test String with CaPiTaLs.", tolower = TRUE)
## Sent and transformed by myfun: Test String with CaPiTaLs. 
##  TRUE
myfun2("Test String with CaPiTaLs.", toLower = TRUE, notDefined = 1)
## Sent and transformed by myfun: test string with capitals. 
##  1
myfun2("Test String with CaPiTaLs.", sep = "\tXX\t")
## Sent and transformed by myfun:   XX  Test String with CaPiTaLs.  XX  

最佳答案 我不会返回错误.警告应该足够了.像这样的东西:

myfun2.character <- function(x, toLower = FALSE, ...) {
  elli <- names(list(...))
  check <- elli %in% names(formals(cat))
  if (any(!check)) warning(sprintf("%s is not an expected parameter. Did you misstype it?", 
                                   paste(elli[!check], collapse = ", ")))
  cat("Sent and transformed by myfun:", ifelse(toLower, tolower(x), x), "\n", ...)
}


myfun2("Test String with CaPiTaLs.", tolower = TRUE)
#Sent and transformed by myfun: Test String with CaPiTaLs. 
#TRUE
#Warning message:
#  In myfun2.character("Test String with CaPiTaLs.", tolower = TRUE) :
#  tolower is not an expected parameter. Did you misstype it?
myfun2("Test String with CaPiTaLs.", toLower = TRUE, notDefined = 1)
#Sent and transformed by myfun: test string with capitals. 
#1
#Warning message:
#  In myfun2.character("Test String with CaPiTaLs.", toLower = TRUE,  :
#                        notDefined is not an expected parameter. Did you misstype it?
myfun2("Test String with CaPiTaLs.", sep = "\tXX\t")
## Sent and transformed by myfun:   XX  Test String with CaPiTaLs.  XX

我不认为最后一个应该警告.你应该避免位置参数匹配,如果你在那里使用名称匹配,你会得到一个错误,你需要捕获.

点赞