Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Install a specific version of an R package (hack)
# Looks in the CRAN archive for the specified package and version. If
# the specified version is NULL or the same as the most recent version
# of the package, this function simply calls install.packages(). Otherwise,
# it looks at the list of archived source tarballs and tries to install
# an older version instead.
install.package.version <- function(
version = NULL,
repos = getOption('repos'),
type = getOption("pkgType"))
contriburl <- contrib.url(repos, type)
available <- available.packages(contriburl)
if (package %in% row.names(available)) {
current.version <- available[package, 'Version']
if (is.null(version) || version == current.version) {
install.packages(package, repos = repos, contriburl = contriburl, type = type)
con <- gzcon(url(sprintf("%s/src/contrib/Archive.rds", repos), "rb"))
archive <- readRDS(con)
if (!(package %in% names(archive))) {
stop(sprintf("couldn't find package '%s'", package))
info <- archive[[package]]
if (is.null(version)) {
# Just grab the latest one. This will only happen if the package
# has been pulled from CRAN.
package.path <- info[length(info)]
} else {
package.path <- paste(package, "/", package, "_", version, ".tar.gz", sep="")
if (!(package.path %in% info)) {
stop(sprintf("version '%s' is invalid for package '%s'", version, package))
package.url <- sprintf("%s/src/contrib/Archive/%s", repos, package.path)
local.path <- file.path(tempdir(), basename(package.path))
if (download.file(package.url, local.path) != 0) {
stop("couldn't download file: ", package.url)
install.packages(local.path, repos = repos, type = type)
Copy link

pcejrowski commented Sep 12, 2017

Hey, nice hack! I see it's 6 years old. Do you know if this feature is now included in R?

Copy link

tanishgupta1 commented Dec 29, 2017

yes if this feature is in R , then please let us now.

Copy link

mirekphd commented Jun 19, 2018

Apparently devtools::install_version() can be used to install a specific version of an R package (hosted on CRAN), although it cannot guarantee that binaries will be identical between installs, because it still requires compilation on linux systems.

Copy link

mirekphd commented Jun 19, 2018

Also Github-hosted R libraries can have their versions pinned using the "ref" parameter of devtools::install_github(), like this:

devtools::install_github(repo = "catboost/catboost", subdir = "catboost/R-package", ref = "v0.8.1.1")

Copy link

btmash commented Oct 8, 2019

The problem comes when you need a pinned version of devtools. That's where it seems this script might come in handy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment