How do you use multiple versions of the same R package?

Solution 1:

You could selectively alter the library path. For complete transparency, keep both out of your usual path and then do

 library(foo, lib.loc="~/dev/foo/v1")    ## loads v1

and

 library(foo, lib.loc="~/dev/foo/v2")    ## loads v2

The same works for install.packages(), of course. All these commands have a number of arguments, so the hooks you aim for may already be present. So don't look at changing R_HOME, rather look at help(install.packages) (assuming you install from source).

But AFAIK you cannot load the same package twice under the same name.

Solution 2:

Many years have passed since the accepted answer which is of course still valid. It might however be worthwhile to mention a few new options that arised in the meanwhile:

Managing multiple versions of packages

For managing multiple versions of packages on a project (directory) level, the packrat tool can be useful: https://rstudio.github.io/packrat/. In short

Packrat enhances your project directory by storing your package dependencies inside it, rather than relying on your personal R library that is shared across all of your other R sessions.

This basically means that each of your projects can have its own "private library", isolated from the user and system libraries. If you are using RStudio, packrat is very neatly integrated and easy to use.

Installing custom package versions

In terms of installing a custom version of a package, there are many ways, perhaps the most convenient may be using the devtools package, example:

devtools::install_version("ggplot2", version = "0.9.1")

Alternatively, as suggested by Richie, there is now a more lightweight package called remotes that is a result of the decomposition of devtools into smaller packages, with very similar usage:

remotes::install_version("ggplot2", version = "0.9.1")

More info on the topic can be found:

  • https://support.rstudio.com/hc/en-us/articles/219949047-Installing-older-versions-of-packages