44

I am learning to build a package for R. Now to set it up I need to run some code when the package is being loaded via require(myPackage).

I read the documentation on help(".onLoad") that just made me really confused as there is no example. How do I actually use .onLoad?

Can someone please show me a simple example? For example I know export(myfun) in the NAMESPACE file will export myfun for use, what is the code that I need to run say rnorm(10) at package load?

epo3
  • 2,991
  • 2
  • 33
  • 60
xiaodai
  • 14,889
  • 18
  • 76
  • 140

2 Answers2

53

There is usually a "processing function" (traditionally called zzz.R) with tasks to be performed when the package is loaded, such as loading libraries and compiled code. For example you can create a zzz.R file where you create this function:

.onLoad <- function(libname, pkgname){
  x <- rnorm(10)   ## dummy example 
}
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • 4
    For example the dplyr package uses an .onLoad function visible in a [zzz.r file](https://github.com/tidyverse/dplyr/blob/bbcfe99e29fe737d456b0d7adc33d3c445a32d9d/R/zzz.r). – Paul Rougieux Aug 27 '18 at 12:54
  • Has this functionality been removed? This wouldn't work for me but `assign('x', rnorm(1), envir = .GlobalEnv)` did work – gabagool Jan 25 '21 at 05:29
  • 4
    @drj3122 No, the answer is simply wrong; this code *never* worked. But your code is also not correct, don’t write the data into the global environment. You want to write the data into the *package* environment. To do this you need to use `topenv()` instead of `.GlobalEnv`. See https://stackoverflow.com/a/67664852/1968. – Konrad Rudolph May 24 '21 at 09:25
  • @KonradRudolph What do you mean by the answer is wrong ? – agstudy May 25 '21 at 18:07
  • 1
    @agstudy I mean that it doesn’t work: `<-` performs *local* assignment, which isn’t useful here (I realise this is a toy example, but one of the top use-cases of `.onLoad` is to set a package variable). Incidentally, using `<<-` wouldn’t fix this. See the linked answer for a proper fix. – Konrad Rudolph May 25 '21 at 18:44
1

The R Packages ebook talks a bit more about using .onLoad() and .onAttach(): https://r-pkgs.org/r.html?q=onattach#when-you-do-need-side-effects

Nick Kastango
  • 71
  • 1
  • 3
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31354000) – xilliam Mar 29 '22 at 08:17
  • 1
    This link is now dead. Is there a new one? – Sky Scraper Sep 22 '22 at 22:53
  • https://r-pkgs.org/code.html#when-you-do-need-side-effects – Richard Telford Oct 30 '22 at 18:32