1

What is the correct way to go about automatically running some setup code (either in R or C++) once per package loading? Ideally, said code would execute once the user did library(mypackage). Right now, it's contained in a setup() function that needs to be run once before anything else.

Just for more context, in my specific case, I'm using an external library that uses glog and I need to execute google::InitGoogleLogging() once and only once. It's slightly awkward because I'm trying to use it within a library because I have to, even though it's supposed to be called from a main.

user2476581
  • 135
  • 2
  • 9

1 Answers1

5

Just read 'Writing R Extensions' and follow the leads -- it is either .onAttach() or .onLoad(). I have lots of packages that do little things there -- and it doesn't matter this calls to C++ (via Rcpp or not) as you are simply asking about where to initialise things.

Example: Rblpapi creates a connection and stores it

.pkgenv <- new.env(parent=emptyenv())

.onAttach <- function(libname, pkgname) {
    if (getOption("blpAutoConnect", FALSE)) {
        con <- blpConnect()
        if (getOption("blpVerbose", FALSE)) {
            packageStartupMessage(paste0("Created and stored default connection object ",
                                         "for Rblpapi version ",
                                         packageDescription("Rblpapi")$Version, "."))
        }
    } else {
        con <- NULL
    }
    assign("con", con, envir=.pkgenv)
}

I had some (not public) code that set up a handle (using C++ code) to a proprietary database the same way. The key is that these hooks guarantee you execution on package load / attach which is what you want here.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Thanks. I was searching for "setup" in "Writing R Extensions", which didn't turn up anything. – user2476581 Apr 01 '16 at 00:35
  • I hear you. These things are too scattered around -- but that was part of the reason we created the r-package-devel mailing list. Topics like this do get discussed there, and it has a good signal/noise ratio. SO works too at times :) – Dirk Eddelbuettel Apr 01 '16 at 00:46