Loading data into a package

I'm making a package that reads an environment variable once attached. This env variable contains a path to a configuration file to be parsed. Once parsed, I store it in a dataframe. All of this is done in the .onAttach function and the dataframe needs to be created everytime the user attaches the package as it points to a file that she/he may change anytime before attaching the package

All the functions in the package need to have access to the dataframe thas is created in the .onAttach function and I don't want to create it using in the global environment of the user.

Is there a way to run the chunk of code that parses the file only in .onAttach and make the data available to all other functions ?

Thanks

1 Like

Yes, you can use the assignInMyNamespace() function from the utils package. Basic template you can use:

.onLoad <- function(libname, pkgname) {
  config <- parse_config_file("path/to/config.txt") # Or however you do it
  assignInMyNamespace("config", config)
}

I suggest you use .onLoad instead of .onAttach. The former will also run when the package is loaded but not attached (for example, when it's imported by another package or you use pkg::obj accessing).

The assignInMyNamespace function is also good for applying a function from the package to an internal data object. R's always thrown a fit when I try it any other way.

2 Likes

Thanks @nwerth ! It works :+1:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.