繁体   English   中英

如何让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'

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM