简体   繁体   English

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

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

I'm trying to work smartly with the ellipsis ( ... ) argument in R and have some problems. 我正在尝试使用R中的省略号( ... )参数巧妙地工作并遇到一些问题。

I am trying to pass some default arguments at the beginning of the function without cluttering up the argument area of the function by using ... and overriding if they are provided there. 我试图在函数的开头传递一些默认参数,而不会通过使用...覆盖函数的参数区域,如果在那里提供它们则覆盖。 But somehow the ellipsis argument doesn't seem to pick up my full vector 但不知何故,省略号参数似乎没有拿起我的完整向量

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)
}

Function call: 功能调用:

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

Throws the error: 抛出错误:

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

So something is going wrong here. 所以这里出了点问题。 If I pass the ellipsis arguments to the plot function immediately it does work without error. 如果我立即将省略号参数传递给绘图函数,它确实可以正常工作。

You need to do this, by collecting/packing ... into a list , if you want to use its contents inside the function. 如果要在函数内部使用其内容,则需要通过收集/打包...到列表中来执行此操作。

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"))

The problem in your original code, is that args() or hasArg() only works for formal arguments in function call. 原始代码中的问题是args()hasArg()仅适用于函数调用中的形式参数 So when you pass in col = c("purple", "green", "blue") , hasArg() knows there is a formal argument col , but does not evaluate it . 所以当你传入col = c("purple", "green", "blue")hasArg()知道有一个正式的参数col ,但不会对它进行评估 Therefore, inside the function, there is no actual col variable to be found (you can use a debugger to verify this). 因此,在函数内部,没有找到实际的col变量(您可以使用调试器来验证这一点)。 Interestingly, there is a function col() from R base package, so this function is passed to paste . 有趣的是,R base包中有一个函数col() ,所以这个函数被传递给paste As a result, you get an error message when trying to concatenate a character string and a "closure". 因此,在尝试连接字符串和“闭包”时会收到错误消息。

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

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