Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Functions: Print Warning Only on First Call of Function

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.

like image 892
user3084629 Avatar asked Jul 17 '14 19:07

user3084629


1 Answers

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.

like image 112
MrFlick Avatar answered Nov 15 '22 01:11

MrFlick