Namespaces in R Language

In R language, the packages can have namespaces, and currently, all of the base and recommended packages do except the dataset packages. Understanding the use of namespaces is vital if one plans to submit a package to CRAN because CRAN requires that the package plays nicely with other submitted packages on CRAN.

Namespaces in R Language

Namespaces ensure that other packages will not interfere with your code and that the package works regardless of the environment in which it’s run. In R Language, the namespace environment is the internal interface of the package. It includes all objects in the package, both exported and non-exported to ensure that every function can find every other function in the package.

For example, plyr and Hmisc both provide a function namely summarize(). Loading plyr package and then Hmise, the summarize() function will refer to the Hmisc. However, loading the package in the opposite order, the summarize() function will refer to the plyr package version.

To avoid confusion, one can explicitly refer to the specific function, for example,



Namespaces in R Language

Now, the order in which the packages are loaded would not matter.

Namespaces do three things:

  • Namespaces allow the package writer to hide functions and data that are meant only for internal use,
  • Namespaces prevent functions from breaking when a user (or other package writers) picks a name that clashes with one in the package, and
  • Namespaces provide a way to refer to an object within a particular package

Namespace Operators

In R language, two operators work with namespaces.

  • Doule-Colon Operator
    The double-colon operator:: selects definitions from a particular namespace. The transpose function t() will always be available as the base::t because it is defined in the base package. Only functions that are exported from the package can be retrieved in this way.
  • Triple-Colon Operator
    The triple-colon operator ::: acts like the double-colon operator but also allows access to hidden objects. Users are more likely to use the getAnywhere() function, which searches multiple packages.

Packages are often interdependent, and loading one may cause others to be automatically loaded. The colon operators will also cause automatic loading of the associated package. When packages with namespaces are loaded automatically they are not added to the search list.

Basic R Frequently Asked Questions

Online MCQs Test Preparation Website with Answers

Leave a Reply