is it possible to have library()
influence only the local scope?
For example, my script has a lapply
loop that source() code in other scripts; these scripts load their own libraries, but I would like the namespace to be cleaned after the code in these scripts is executed, so that function in package A called by script 1 do not mask functions in package B called by script 2.
I know there are complete solutions like the modules
and import
package, but I would like a simpler base R solution first to scale up only if needed.
Using
loadNamespace("pkg")
will load the namespace of the 'pkg' package. Usinglibrary("pkg")
will also attach the 'pkg' package to R's search path. You can see which namespaces are loaded usingloadedNamespaces()
and which packages are attached usingsearch()
. These properties are global to R. In other word, it is not really possible to make them local.If you wish to use
library()
inside your function/map-reduce calls withoutlibrary()
causing the package to be attached in your current R session, then, as others suggested, you could evaluate your calls in an external R process.(disclaimer: I'm the author) I propose to use futures (future) for this where you evaluate them external via future.callr - a future wrapper for callr. The future framework will take care of exporting objects needed to the external R process. Here's an example:
Note how a future is created and its value is immediately retrieved, i.e.
value(future(...))
. To clarify this fact, you could use:If you want to avoid having the user specify the
plan()
, the you do:so you can do:
without loading or attaching gtools (it obviously loads other packages needed by future and callr);
UPDATE 2020-07-26
Here's how to source R scripts in an external R process via a future while at the same time pulling globals from the main R session: