简体   繁体   English

r:函数参数先匹配变量,然后再省略号

[英]r: function arguments matched to variables rather then ellipsis

here is my function: 这是我的功能:

print.log <- function(print.flag = T,...){
  if(print.flag)
    print(paste(as.character(Sys.time()),' - ',...))
}

function call: 函数调用:

print.log('listing x files')

error message: Error in if (print.flag) print(paste(as.character(Sys.time()), " - ", : argument is not interpretable as logical 错误消息:if(print.flag)print(paste(as.character(Sys.time()),“-”,:错误不能解释为逻辑

here is the value print.flag holds: 这是print.flag的值:

Browse[2]> print.flag
[1] "listing x files"

I understand that the string I wanted to push to the ellipsis was matched after all to the print.flag variable. 我知道我想推送到省略号的字符串毕竟与print.flag变量匹配。

my question: why is that the behavior, and how can I fixed it to achieve the desired result? 我的问题:为什么是这种行为,以及如何解决该问题以获得预期的结果? (meaning, all function arguments will go to the ellipsis, unless I specifically declare the print.flag variable ) (意味着,除非我特别声明了print.flag变量,否则所有函数参数都将转至省略号)

The solution here is actually pretty easy: switch the order of your arguments. 实际上,这里的解决方案非常简单:切换参数的顺序。

print.log <- function(..., print.flag = T){
  if(print.flag)
    print(paste(as.character(Sys.time()),' - ',...))
}

The reason this works is that unnamed parameters in a function call are matched in the order they are named in the function definition. 之所以起作用,是因为函数调用中的未命名参数按照它们在函数定义中的命名顺序进行匹配。 This happens until you hit ... , which greedily eats up all unnamed (or named and not mentioned, for that matter) arguments. 这种情况一直持续到您点击...为止, ...贪婪地吞噬了所有未命名(或为此而未提及的)参数。

print.log("a", "b", "c")
#> [1] "2017-07-30 05:21:08  -  a b c"

print.log("a", print.flag = F)

print.log("a", print.flag = T, "b")
#> [1] "2017-07-30 05:21:08  -  a b"

print.log("a", one = "b", two = "c")
#> [1] "2017-07-30 05:21:08  -  a b c"

NOTE: perhaps to answer a few questions you did not ask. 注意:也许可以回答您没有问的几个问题。

Be careful using . 使用时要小心. as a naming convention (despite many base R functions that do not follow this advice), as the . 作为命名约定(尽管许多基本R函数不遵循此建议),如. is used by S3 for class behavior. S3用于类行为。 More reading here . 在这里阅读更多。

Also, you might look into the logging package, which is an R port of the popular python logging package. 另外,您可能会查看logging软件包,它是流行的python日志记录软件包的R端口。 It allows environmental control of logging with "logging level" and defining a default formatting (in your case, timestamp in front, etc.). 它允许使用“日志记录级别”对日志记录进行环境控制,并定义默认格式(在您的情况下,位于前面的时间戳等)。

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

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