Open In App

Working With Different Versions of an R Package

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

R programming language offers different functionalities through different packages available in online repositories. The official repository CRAN keeps updating these packages and frequently publishes newer versions of packages.

R’s package system is set by default to overwrite the existing versions of packages so that the user always has the latest version. Hence, any update will overwrite the previous version. So if you want to use two versions of the package, you have to install it in a different location and have to accordingly import it by specifying that location.

Syntax:

.libPaths()

Returns the path where packages are looked at by default. The first path is the user library where packages the user chooses to download are installed. The second is the system library path where default packages that come with R are installed. 

To check the packages installed, use this command:

installed.packages()                      

It returns information about all the packages installed like the version, the path of installation, dependencies on the version of R, other imports needed by the package. 

Installing different versions of package

Sometimes there can be drastic changes in the latest version of the software which makes the user revert to the previous versions. Some functions may be deprecated, classes removed, parameters of functions altered which can be troublesome for existing users working with earlier versions. So a user may want to install an outdated version for a particular function and then revert to an existing library.

Syntax:

remotes::install_version(package , version= version number, lib =location)

This function installs the package at the location lib specified by the user. This function may not work due to the lack of an appropriate toolchain for building/compiling packages. By default, R for Windows installs the precompiled “binary packages” from CRAN. CRAN archives the package sources and not the binaries which we need to install. Hence, Rtools is required to build and compile libraries.

‘versions’ package on CRAN relies on Revolution Analytics MRAN server to install packages for specific versions without the need to install Rtools for installing binary packages but this will work going back to date when MRAN was released, that is near to 2014-09-17.

Syntax:

versions::install.dates(pkgs, dates, lib)

Download and install the latest versions of packages hosted on CRAN as of a specific date from the MRAN server.

Example:

R




# install yesterday's version of dslabs
versions::install.dates('dslabs', Sys.date() - 1)


Syntax:

versions::install.versions(pkgs, versions, lib)

Download and install named versions of packages hosted on CRAN from the MRAN server.

Example:

R




# install specific version of caret
install.versions('caret', '6.0-77')


If you already have a version of the package, and you want to install another version, you have to change the path of the directory where R stores libraries. R will overwrite the previous installation of the same library even if the version is different.

Loading the Packages in R session

R searches the active library path to find the installation of the requested package. As both versions of a package are installed in different locations, the library function can still load the package by specifying the location of that package.

Syntax:

library(package, lib.loc= location)

By default, lib.loc = NULL which means R will search for packages in its default library path.

The following example illustrates how to use different versions of package.

Example:

R




# R program to illustrate working
# with different versions of a package.
  
library(versions)
library(fs)
  
# Create a new folder to install the 
# latest version of package.
old_lib_loc <- .libPaths()[1]
new_lib_loc <- path_home_r('R/new_lib/')
  
# install the latest version in the
# new location.
versions::install.versions('caret', version = '6.0-86', lib = new_lib_loc)
                  
# load the library from the default
# path(old_lib_loc) as lib is unspecified.
library(caret) 
  
# Creating sample sets
dat <- data.frame(x = rnorm(50))
class <- sample(c("Y", "N"), 50, TRUE)
  
# Training a model to fit data
fit <- train(dat, class, method = "glm")   
  
# Check the version of caret package in use
packageVersion('caret')   
  
extractProb(list(fit))    
# Displays error due to a internal bug 
# in that version of code.
  
# Detach the current caret package
detach("package:caret")    
  
#if(!require("caret"))
  #install.packages("caret")
  
# loads the newer version of package
# installed in new_lib
library(caret, lib.loc = new_lib_loc)  
  
# check the version of caret package in use
packageVersion('caret')  
  
# returns the training and test data prediction as
# the bug is fixed in this version of package.
extractProb(list(fit))


Output:
 

[1] ‘6.0.86’
           N         Y obs pred model dataType  object
1  0.6343887 0.3656113   N    N   glm Training Object1
2  0.6359912 0.3640088   N    N   glm Training Object1
.
.
49 0.6805284 0.3194716   N    N   glm Training Object1
50 0.6582383 0.3417617   N    N   glm Training Object1
[1] ‘6.0.86’
           N         Y obs pred model dataType  object
1  0.6343887 0.3656113   N    N   glm Training Object1
2  0.6359912 0.3640088   N    N   glm Training Object1
.
.
49 0.6805284 0.3194716   N    N   glm Training Object1
50 0.6582383 0.3417617   N    N   glm Training Object1

Working with packrat or renv

Any install, upgrade or changes in an R session brings about a change in R directory which is shared across all R sessions. Different projects may need different packages and thus there can be a lot of different package dependencies. Hence, we might change some functionalities which are shared in the global environment thereby affecting all other sessions. So we need a ‘Virtual Environment‘ like python to manage these conflicting dependencies. Hence, the idea of project-local libraries is born.

Packrat‘ andrenv‘ are packages available in R for these purpose. renv is the successor of packrat. These packages help to isolate different projects, so that one project won’t affect another by providing every project its own private package library, making the projects portable so that it is easy to install packages your project depends on and reproducing the exact package versions a project needs.  

Renv is a dependency management toolkit for R. Using ‘renv’, you can create and manage project-local R libraries, save the state of these libraries and later restore your library as required. Together, these tools can help make your projects more isolated, portable, and reproducible.

If you have picked up doing some project, before actually working on a project you have to solve version control issues; find the correct versions of packages to use or have to deal with dependencies. Renv provides cleaner and simpler way of doing this. Renv solves package management but does not deal with different versions of R. The workflow for using renv:

  • When you’ve developed your project to a certain point, and you think you or someone else might have to come back to it again in the future, by running renv::init() you can initialize renv.

Syntax: renv::init(project = NULL, profile = NULL,settings = NULL,bare = FALSE,force = FALSE, restart = interactive())

Parameter:

  • project: The project directory.
  • profile:The profile to be activated for example ‘development’ or ‘production’. When NULL, the default profile is activated instead.
  • settings: A list of settings to be used with the newly-initialized project.
  • bare (Boolean): If True, it initializes the project without attempting to discover  and install R package dependencies.
  • force (Boolean): By default, renv will refuse to initialize the home directory as a project.
  • restart (Boolean): attempt to restart the R session after initializing the project? A session restart will be attempted if the “restart” R option is set by the frontend embedding R.

Discovers packages used within the current project, and then initializes a project-local private R library with those packages. The currently installed versions of any packages in use (as detected within the default R libraries) are then installed to the project’s private library.

To start a new project and initialize renv in it, use the project argument to specify the location of the project directory.

This will set up a project-local environment with a private library, and also make sure to install all the packages you’re using into that library.  You will get all your packages and version dependencies discovered and stored in a file called renv.lock.  Renv will also write to files in the active project directory including the lockfile and the folder ‘renv’ in the project directory which contains private libraries and activation scripts to load the project.

Run .libPaths() to check the library paths for the project with renv initialized in it.

  • To save the state of your project library to renv.lock call renv::snapshot() or call renv::restore() to revert to the previous state as encoded in the lockfile.
  • By running renv::restore() you’ll be able to reinstall all dependencies from renv.lock to ensure that you have set up your project as close as possible to where you left it, and massively reducing the chances of running into problems associated with package versions.

Example:

R




# R program with renv initialized 
# in project directory.
  
# install digest 
# Installs the package into a private 
# library.
renv::install("digest")
  
# save library state to lockfile
# Updates a lockfile capturing the state 
# of a project's R package dependencies. 
# The lockfile can be used to later restore 
# these project's dependencies as required.
renv::snapshot()
  
# remove digest from library
renv::remove("digest")
  
# check library status
# Reports the differences between the 
# project's lockfile and the current state
# of the project's library (if any)
renv::status()
  
# restore lockfile, thereby reinstalling digest
# Restore a project's dependencies from a lockfile,
# as previously generated by snapshot().
renv::restore()


The following program demonstrates how to configure renv settings like enabling or disabling automatic snapshots while working in project directory.

Example:

R




# R program to change renv settings.
  
# disable automatic snapshots
auto.snapshot <- getOption("renv.config.auto.snapshot")
options(renv.config.auto.snapshot = FALSE)
  
# restore automatic snapshots
options(renv.config.auto.snapshot = auto.snapshot)




Last Updated : 18 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads