Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

r-package

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?

like image 307
xiaodai Avatar asked Nov 26 '13 17:11

xiaodai


People also ask

How do I load Mass packages in R?

library(MASS) Another way to load a package is to simply check the box next to the package name in the Packages panel in RStudio. When you use this method, you will notice that RStudio enters the Library( ) command in the Command console when you check the package box.

How do I code an R package?

Open a new project in RStudio. Go to the 'File' menu and click on 'New Project. ' Then select 'New Directory,' and 'R Package' to create a new R package.

Which R function is used to load a package?

There are basically two extremely important functions when it comes down to R packages: install. packages() , which as you can expect, installs a given package. library() which loads packages, i.e. attaches them to the search list on your R workspace.


1 Answers

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  } 
like image 104
agstudy Avatar answered Oct 01 '22 10:10

agstudy