R Functions: Print Warning Only on First Call of Function

夙愿已清 提交于 2020-03-19 05:11:15

问题


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.


回答1:


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

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.




回答2:


Lots of packages have messages that popup and since there is a mechanism for detecting second efforts at loading futher calls to library or require are silently ignored. They often are using .onLoad(libname, pkgname). See

?.onLoad


来源:https://stackoverflow.com/questions/24812271/r-functions-print-warning-only-on-first-call-of-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!