Wednesday 2 July 2014

R Package Namespaces

Cited from "Software for Data Analysis: Programming with R"

To apply the namespace mechanism, you must write a sequence of namespace directives in a file called "NAMESPACE" that resides in the top-level directory of your packages source. The directives look roughly like R expressions, but they are not evaluated by the R evaluator. Instead, the file is processed specially to defin the objects that our packages sees and the objects in our package that are seen by other software.

The namespace directives define two R environments, one for the objects that perform the computations inside the package and the other for the objects that users see when the package is attached in an R session. The first of these is referred to as the package's namespace. The second, the result of the export directives in the NAMSPACE file, is the environment attached in the search list.

When you access the two environments explicitly, they will print symbolically in a special form. For package SoDA, the environments would be <environment: namespace: SoDA> and <environment: package: SoDA>, respectivley.

The package's namespace contains all the objects generated by installing the package, that is, all the objects created by evaluating the R source in the package's R subdirectory.
  • The parent of the namespace is an environment containing all the objects defined by the import command in the NAMESPACE file.
  • The parent of that environment is the namespace of R's base package. 
Using a NAMESPACE file, computations in the package will see the explicitly imported objects and the base package, in that order, regardless of what the packages are attached in the session.

No comments:

Post a Comment