如何让 R 识别省略号中的参数向量?

How to let R recognize a vector of arguments in the ellipsis?

我正在尝试巧妙地使用 R 中的省略号 (...) 参数,但遇到了一些问题。

我试图通过使用 ... 在函数的开头传递一些默认参数,而不会弄乱函数的参数区域,如果它们在那里提供则覆盖。但不知何故,省略号参数似乎并没有得到我的完整向量

test <- function(dat, 
                 # I don't want to have to put default col, 
                 # ylim, ylab, lty arguments etc. here
                 ...) {
  # but here, to be overruled if hasArg finds it
  color <- "red"
  if(hasArg(col)) {  # tried it with both "col" and col
    message(paste("I have col:", col))
    color <- col
  }
  plot(dat, col = color)
}

函数调用:

test(data.frame(x = 1:10, y = 11:20), col = c("purple", "green", "blue"))

抛出错误:

Error in paste("I have col:", col) (from #8) : 
  cannot coerce type 'closure' to vector of type 'character'

所以这里出了点问题。如果我立即将省略号参数传递给绘图函数,它确实可以正常工作。

如果你想在函数中使用它的内容,你需要这样做,通过 collecting/packing ... 进入一个列表

test <- function(dat, 
                 # I don't want to have to put default col, 
                 # ylim, ylab, lty arguments etc. here
                 ...) {
  opt <- list(...)
  color <- "red"
  if(!is.null(opt$col)) {  # tried it with both "col" and col
    message(paste("I have col:", opt$col))
    color <- opt$col
  }
  plot(dat, col = color)
}

test(data.frame(x = 1:10, y = 11:20), col = c("purple", "green", "blue"))

您的原始代码中的问题是 args()hasArg() 仅适用于函数调用中的 形式参数 。所以当你传入 col = c("purple", "green", "blue") 时,hasArg() 知道有一个正式的参数 col,但是 不会计算它 。因此,在函数内部,没有找到实际的 col 变量(您可以使用调试器来验证这一点)。有趣的是,R base包中有一个函数col(),所以这个函数被传递给了paste。因此,当您尝试连接字符串和 "closure".

时收到错误消息