6.20 When you do need side-effects

If your package talks to an external system you might need to do some initial setup when the package loads with .onLoad() or .onAttach() conventionally stored in R/zzz.R.

Some common uses of .onLoad() and .onAttach() are:

  • To set custom options for your package with options().
.onLoad <- function(libname, pkgname) {
  op <- options()
  op.dplyr <- list(
    dplyr.show_progress = TRUE
  )
  toset <- !(names(op.dplyr) %in% names(op))
  if (any(toset)) options(op.dplyr[toset])

  invisible()
}
  • To display an informative message when the package is attached.
.onAttach <- function(libname, pkgname) {
  packageStartupMessage("Welcome to my package")
}
  • Use .onUnload() to to clean up side effects.