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’s plan to submit a package to CRAN because CRAN requires that the package plays nicely with other submitted packages on CRAN. Namespaces ensure that other packages will not interfere with your code and the package works regardless of the environment in which it’s run.

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,

> Hmisc::summarize()


> plyr::summarize()

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, there are two operators that 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 inter-dependent, 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.