Can I get the URL of what will be used by install.packages?

Viewed 1033

When running install.packages("any_package") on windows I get the message :

trying URL

'somepath.zip'

I would like to get this path without downloading, is it possible ?

In other terms I'd like to get the CRAN link to the windows binary of the latest release (the best would actually be to be able to call a new function with the same parameters as install.packages and get the proper url(s) as an output).

I would need a way that works from the R console (no manual checking of the CRAN page etc).

2 Answers

I am not sure if this is what you are looking for. This build the URL from the repository information and building the file name of the list of available packages.

#get repository name
repos<- getOption("repos")

#Get url for the binary package
#contrib.url(repos, "both")
contriburl<-contrib.url(repos, "binary")
#"https://mirrors.nics.utk.edu/cran/bin/windows/contrib/3.5"

#make data.frame of avaialbe packages
df<-as.data.frame(available.packages())

#find package of interest
pkg <- "tidyr"  #example
#ofinterest<-grep(pkg, df$Package)
ofinterest<-match(pkg, df$Package)   #returns a single value

#assemble name, assumes it is always a zip file
name<-paste0(df[ofinterest,]$Package, "_", df[ofinterest,]$Version, ".zip")

#make final URL 
finalurl<-paste0(contriburl, "/", name)

Here's a couple functions which respectively :

  • get the latest R version from RStudio's website
  • get the url of the last released windows binary

The first is a variation of code I found in the installr package. It seems there's no clean way of getting the last version, so we have to scrape a webpage.

The second is really just @Dave2e's code optimized and refactored into a function (with a fix for outdated R versions), so please direct upvotes to his answer.

get_package_url <- function(pkg){
  version <- try(
    available.packages()[pkg,"Version"],
    silent = TRUE)
  if(inherits(version,"try-error"))
    stop("Package '",pkg,"' is not available")
  contriburl <- contrib.url(getOption("repos"), "binary")
  url <- file.path(
    dirname(contriburl),
    get_last_R_version(2),
    paste0(pkg,"_",version,".zip"))
  url
}

get_last_R_version <- function(n=3){
  page <- readLines(
    "https://cran.rstudio.com/bin/windows/base/",
    warn = FALSE)   
  line <- grep("R-[0-9.]+.+-win\\.exe",  page,value=TRUE)
  long <- gsub("^.*?R-([0-9.]+.+)-win\\.exe.*$","\\1",line)
  paste(strsplit(long,"\\.")[[1]][1:n], collapse=".")
}

get_package_url("data.table")
# on my system with R 3.3.1 
# [1] "https://lib.ugent.be/CRAN/bin/windows/contrib/3.5/data.table_1.11.4.zip"
Related