rr-package

Create an option to be modified by options() in an R package


I am making an R package with functions that should output different things, ideally depending on the setting of an option with options(myoption = ...).

For example, if myoption, set by the user at the beginning of their session, can either be TRUE or FALSE (let it be FALSE by default), one of the package's functions may read:

if (myoption) {
    # use method A
} else {
    # use method B
}

Q: How are you able to build this functionality into an R package?

I have come across this answer which seems to be what I'm looking for, but the accepted answer isn't detailed enough for me to be able to use. Quite possibly, this answer betrays my lack of understanding of how options() works internally.


Solution

  • The answer is obvious in hindsight but posting it here in case anyone learning to develop R packages has the same question in the future.


    To implement what I wanted, my function definitions included something like:

    ...
    
    if (!getOption("myoption", default = FALSE)) {
     # use method A, will be used if myoption is not set by the user (i.e. the default)
    } else {
     # use method B
    }
    

    Once a user calls options(list(myoption = TRUE)), the function will use method B.

    See here for an older solution to the same problem: Create (and set value for) a new global option using base R?