R Yoda R Yoda - 1 year ago 60
R Question

Load library into existing environment (equivalent to "local" parameter of "source")?

I am sourcing util functions in production into an environment to encapsulate (and group) the helper functions:

Helper file:

# File: Helper.R
hello <- function() {
print("Hello world")


helper <- new.env()
source("Helper.R", local=helper)
helper$hello() # call the helper function

How can I migrate my sourced "Helper.R" into a library without breaking the calls of the sourced functions?

What I want is something like

helper <- new.env()
library(Helper, local=helper)
helper$hello() # call the helper function (loaded from the library now)

Is there a way to do this?

Answer Source

You can use the import_package function in the ‹modules› package (not the one on CRAN, it’s different!).

Then the following attaches a package locally:

modules::import_packge('pkg', attach = TRUE)

Alternatively, and potentially closer to what you actually want to do, you could use it as follows:

pgk = modules::import_package('pkg')

Now the package is not attached at all, and its exported objects can be accessed via pkg$obj. This is somewhat similar to base R’s loadNamespace function, but does considerably more behind the scenes.

Finally, consider not putting your helper code into a package at all, but rather distributing it as a module. This is after all what the ‹modules› package was designed for. So instead of creating a package, just distribute your helper.r code file (or folder) and then use it as follows:

helper = modules::import('helper')

See the package README and vignette for a detailed description.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download