The R package I am developing requires several R data objects, such as pre-computed models and parameters.
Currently I have each object in the 'data' directory of the package in individual .RData files. When using the package users can use the "data" function to attach these objects to their environment.
The behaviour I would like instead would be that on loading the package the data objects are automatically attached to the internal package environment and not accessible to the user directly.
My understanding is that placing a 'sysdata.rda' file in the 'R' directory of the package containing the objects currently in 'data' will give me the desired result. However, is there a way to do this so that I can have each object in a separate file instead of grouped together?
You can use the
.onLoad()
hook to calldata()
when your package is being loaded, and specify the package namespace as the environment where to load the data objects into.Assuming you have files
model1.R
andmydata.RData
in thedata/
directory of your package calledfoopkg
, define the functionsomewhere in your package (e.g. in
foopkg-package.R
).After building and installing the package,
should demonstrate that the various data objects were successfully loaded into the package namespace, i.e. visible to functions in your package but not polluting the global environment.
Put your
sysdata.rda
file in thedata
directory of your package.Do not use Lazy Data -- your DESCRIPTION file should either not have a line for LazyData, or, if it does, it should be
LazyData: no
In any .R file in the R directory of your package add a line like this
I created a
data.frame
namedsysdata
and saved it to a file calledsysdata.rda
in the data directory of a package calledanRpackage
I added the above line to an .R file, and also added this unexported function just to show that functions in the package have access to the data.
Then I see the following an R session
So, users still have access to the data, but as you requested, they do not have direct access. The user still has the option to run
data(sysdata)
.