How to Automatically Load Data in an R Package

How to automatically load data in an R package?

From R-exts.pdf (online source):

The ‘data’ subdirectory is for data files, either to be made available
via lazy-loading or for loading using data(). (The choice is made by
the ‘LazyData’ field in the ‘DESCRIPTION’ file: the default is not to
do so.)

Adding the following to the DESCRIPTION file should do it:

LazyData: true

How to load packages in R automatically?

Put library(foo) in your .Rprofile file or set R_DEFAULT_PACKAGES: see ?Rprofile ...

In particular (because ?Rprofile is long and potentially intimidating):

If you want a different set of packages than the default ones when you
start, insert a call to ‘options’ in the ‘.Rprofile’ or
‘Rprofile.site’ file. For example, ‘options(defaultPackages =
character())’ will attach no extra packages on startup (only the
‘base’ package) (or set ‘R_DEFAULT_PACKAGES=NULL’ as an environment
variable before running R). Using ‘options(defaultPackages = "")’ or
‘R_DEFAULT_PACKAGES=""’ enforces the R system default.

Since you probably do want all of the default packages loaded, and then extra ones in addition (rather than, say, not loading some of the default packages), you can either put

library("mypackage1")
library("mypackage2")
[etc.]

or using options(defaultPackages=...):

options(defaultPackages=c(getOption("defaultPackages"),
"mypackage1","mypackage2", ... [etc.]))

in your .Rprofile to append your desired packages to the standard defaults.

edit (copied from comment) re getting this to work in Rstudio:
http://rstudio.org/docs/using/workspaces suggests that Rstudio executes .Rprofile and then "Performs the other actions described in R Startup [ http://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html ]" (which is the same as ?Rprofile). It is ambiguous whether it looks at Rprofile.site or not.

edit #2: according to comment below, it does work with a recent version of Rstudio.

Load data object when package is loaded

As you say

The object is used in one of the package functions, so it needs to be available at all time.

I think the author of that package should really NOT use data(.) for that.
Instead he should define the object inside his /R/ either by simple R code in an R/*.R file,
or by using the sysdata.rda approach that is explained in the famous first reference for all these question,
"Writing R Extensions". In both cases the package author can also export the object which is often desirable for other users as in your case.

Of course this needs a polite conversation between you and the package author, and will only apply to the next version of that package.



Related Topics



Leave a reply



Submit