Learn R Programming

modules (version 0.13.0)

import: Import mechanism for modules

Description

You can declare imports similar to what we would do in a R package: we list complete packages or single function names from a package. These listed imports are made available inside the module scope.

Usage

import(from, ..., attach = TRUE, where = parent.frame())

importDefaultPackages(except = NULL, where = parent.frame())

Value

An environment is returned invisibly comprising the imports.

Arguments

from

(character, or unquoted expression) a package name

...

(character, or unquoted expression) names to import from package.

attach

(logical) whether to attach the imports to the search path.

where

(environment) typically the calling environment. Should only be relevant for testing.

except

(character | NULL) a character vactor excluding any packages from being imported.

Details

import and use can replace library and attach. However they behave differently and are only designed to be used within modules. Both will work when called in the .GlobalEnv but here they should only be used for development and debugging of modules.

import adds a layer to a local search path. More precisely to the calling environment, which is the environment supplied by where. It will alter the state of the calling environment. This is very similar to how the library function and the search path are constructed in base R. Noticeable differences are that we can choose to only import particular functions instead of complete packages. Further we do not have to mutate the calling environment by setting attach to FALSE. Regardless of the attach argument, import will return an environment with the imports and can be bound to a name. library will also load packages in the 'Depends' field of a package, this is something import will not do.

Only one import declaration per package is allowed. A second call to import will remove the previous one from the search path. Then the new import layer is added. If several smaller import declarations are desirable, use attach = FALSE and bind the return value of import to a name.

Examples

Run this code
m <- module({
  # Single object from package
  import("stats", "median")
  # Complete package
  import("stats")
  # Without side-effects
  stats <- import("stats", attach = FALSE)
  median <- function(x) stats$median(x)
})

Run the code above in your browser using DataLab