【问题标题】:How to let R recognize a vector of arguments in the ellipsis?如何让 R 识别省略号中的参数向量?
【发布时间】:2016-09-20 23:28:28
【问题描述】:

我正在尝试巧妙地使用 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'

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

【问题讨论】:

  • 听起来你需要阅读some Advanced R。在我链接的页面上搜索dots

标签: r function plot arguments ellipsis


【解决方案1】:

如果您想在函数中使用其内容,则需要通过... 收集/打包到列表中来执行此操作。

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。因此,在尝试连接字符串和“闭包”时会收到错误消息。

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 2019-02-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2011-03-25
    相关资源
    最近更新 更多