6

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.

user3084629
  • 445
  • 2
  • 4
  • 7
  • 2
    Why do you want to do this. If you explain your reasoning we might be able to suggest a better way to achieve your goal. – Dason Jul 17 '14 at 19:50
  • @Dason in my case, I want to display a message *just* to make sure the user is aware of something (that they almost certainly would be, but which would be bad if they weren't). Hence I don't want to badger them about it (just let them know once) – stevec Jul 25 '20 at 16:44

2 Answers2

9

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

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
IRTFM
  • 258,963
  • 21
  • 364
  • 487