R: How to run some code on load of package?
Asked Answered
L

2

46

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?

Layby answered 26/11, 2013 at 17:11 Comment(0)
C
55

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 
}
Chromatid answered 26/11, 2013 at 17:23 Comment(5)
For example the dplyr package uses an .onLoad function visible in a zzz.r file.Fulton
Has this functionality been removed? This wouldn't work for me but assign('x', rnorm(1), envir = .GlobalEnv) did workAsteroid
@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://mcmap.net/q/373688/-how-to-make-variable-available-to-namespace-at-loading-time.Dnepropetrovsk
@KonradRudolph What do you mean by the answer is wrong ?Chromatid
@Chromatid 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.Dnepropetrovsk
S
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

Shocker answered 23/3, 2022 at 5:22 Comment(3)
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 ReviewMustang
This link is now dead. Is there a new one?Dao
r-pkgs.org/code.html#when-you-do-need-side-effectsJotun

© 2022 - 2024 — McMap. All rights reserved.