public
Last active

Install a specific version of an R package (hack)

  • Download Gist
install-package-version.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
# 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(
package,
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)
return()
}
}
 
con <- gzcon(url(sprintf("%s/src/contrib/Archive.rds", repos), "rb"))
archive <- readRDS(con)
close(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)
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.