R函数:仅在第一次调用函数时打印警告 [英] R Functions: Print Warning Only on First Call of Function

查看:74
本文介绍了R函数:仅在第一次调用函数时打印警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试编写一个打印错误消息的函数,但是仅在用户第一次调用该函数时.如果他们打开R,加载库并调用该函数,它将打印警告消息.如果他们再次调用该函数,它将不会打印此警告消息.如果他们关闭R并执行相同的过程,它将为第一个呼叫而不是第二个呼叫打印警告消息.我了解R中基本warning()函数的概念,但是在这种情况下,帮助文件中没有任何文档.是否有人知道可以与warning()函数一起使用的函数或条件可以解决此问题?谢谢!我正在做一个项目,负责教授需要某种版权的东西,而他希望这样.

So I'm trying to write a function that prints an error message, but only on the first time the user calls the function. If they open R, load the library, and call the function, it will print a warning message. If they call the function again, it will not print this warning message. If they close R and do the same process, it will print the warning message for the first call and not on the second. I understand the idea of the basic warning() function in R, but I don't see any documentation in the help file for this kind of condition. Does anyone know of a function or a condition that could be used with the warning() function that would be able to solve this? Thanks! I am working on a project where the professor in charge needs this for some sort of copyright thing and he wants it to be this way.

推荐答案

执行此操作的一个程序包是quantmod.使用getSymbols函数时,它会警告您即将更改为默认值.可以使用options来实现.

One package that does this is quantmod. When you use the getSymbols function, it warns you about the upcoming change to the defaults. It does so using options.

"getSymbols" <- function(Symbols=NULL,...) {
  if(getOption("getSymbols.warning4.0",TRUE)) {
    # transition message for 0.4-0 to 0.5-0
    message(paste(
            '    As of 0.4-0,',sQuote('getSymbols'),'uses env=parent.frame() and\n',
            'auto.assign=TRUE by default.\n\n',
            'This  behavior  will be  phased out in 0.5-0  when the call  will\n',
            'default to use auto.assign=FALSE. getOption("getSymbols.env") and \n',
            'getOptions("getSymbols.auto.assign") are now checked for alternate defaults\n\n',
            'This message is shown once per session and may be disabled by setting \n',
            'options("getSymbols.warning4.0"=FALSE). See ?getSymbol for more details'))
    options("getSymbols.warning4.0"=FALSE) 
  }
  #rest of function....
}

因此,他们检查名为"getSymbols.warning4.0"的选项,如果未找到,则默认为TRUE.然后,如果找不到该消息,他们将显示一条消息(您可能会显示警告),然后将该选项设置为FALSE,以便该消息下次不再显示.

So they check for an option named "getSymbols.warning4.0" and default to TRUE if not found. Then if it's not found, they display a message (you may display a warning) and then set that option to FALSE so the message will not display next time.

这篇关于R函数:仅在第一次调用函数时打印警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆