One of the major strengths of R is the large number of contributed packages available for users to download and install. If you want to use packages not on the basic list, it is easy to install them.

Most of the information that follows is taken from the R Installation and Administration Managing libraries section. There are up to two steps to using R packages in your code; downloading/building the package (probably from CRAN) and then importing the package into your workspace or script. Installing a package is simple:

If all goes well, your package will be loaded in a local directory for your use; this directory, called a library, can be specified in the arguments to the command, but the default is probably fine. The location of the libraries which will be searched for packages which you try to import into your workspace or code can be seen with , where the first line, to be searched first, will typically be your local installation directory. It is possible to manipulate from within R, using environment variables, or a profile file; consult the R documentation linked above for more detail on this.

Once a package is installed in a library, it and all other installed packages can be listed, with brief descriptions, for all library locations searched:

You can check whether a package is installed with:

This has the benefit of returning or but can be slow if there are a large number of installed packages; in that case, can be used, returning the location of the first version of the package if found and (by default) an error if not found.

Once a package is installed, it can be loaded into your workspace using ; for example, to load package by searching your standard :

Specifying an alternative set of library locations can be achieved using the argument to . Unloading, if required, can be achieved with with the argument set to , or using .

Any object in R is searched for according to an order you can see with the function:

contains your workspace which, as the list is searched in order from first to last until a match is found, ensures that any objects currently in the workspace environment will mask equivalents defined elsewhere, further down the list. When is used to load a package, it is inserted by default into the second position on the list (this can be changed with the argument to ) and everything else is pushed down.

Finally, functions and non-functions (such as variables), although both objects, have different namespaces so can share names (although this may lead to confusion for anyone reading your code!)

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Access Statement