onertipaday
1/16/2018 - 8:23 AM

'improved' version of download.file function: you need to specify only the URL of a resource to be downloaded.

'improved' version of download.file function: you need to specify only the URL of a resource to be downloaded.

download.file2 <- function (url, destfile = NULL, method, quiet = FALSE, mode = "w", cacheOK = TRUE, extra = getOption("download.file.extra")) 
{
  if (is.null(destfile)) destfile <- basename(url)
  else destfile
  method <- if (missing(method)) 
    getOption("download.file.method", default = "auto")
  else match.arg(method, c("auto", "internal", "libcurl", "wget", 
                           "curl", "lynx"))
  if (method == "auto") {
    if (length(url) != 1L || typeof(url) != "character") 
      stop("'url' must be a length-one character vector")
    method <- if (grepl("^file:", url)) 
      "internal"
    else "libcurl"
  }
  switch(method, internal = {
    status <- .External(C_download, url, destfile, quiet, 
                        mode, cacheOK)
    if (!quiet) flush.console()
  }, libcurl = {
    status <- .Internal(curlDownload(url, destfile, quiet, 
                                     mode, cacheOK))
    if (!quiet) flush.console()
  }, wget = {
    if (length(url) != 1L || typeof(url) != "character") stop("'url' must be a length-one character vector")
    if (length(destfile) != 1L || typeof(destfile) != "character") stop("'destfile' must be a length-one character vector")
    if (quiet) extra <- c(extra, "--quiet")
    if (!cacheOK) extra <- c(extra, "--cache=off")
    status <- system(paste("wget", paste(extra, collapse = " "), 
                           shQuote(url), "-O", shQuote(path.expand(destfile))))
    if (status) stop("'wget' call had nonzero exit status")
  }, curl = {
    if (length(url) != 1L || typeof(url) != "character") stop("'url' must be a length-one character vector")
    if (length(destfile) != 1L || typeof(url) != "character") stop("'destfile' must be a length-one character vector")
    if (quiet) extra <- c(extra, "-s -S")
    if (!cacheOK) extra <- c(extra, "-H 'Pragma: no-cache'")
    status <- system(paste("curl", paste(extra, collapse = " "), 
                           shQuote(url), " -o", shQuote(path.expand(destfile))))
    if (status) stop("'curl' call had nonzero exit status")
  }, lynx = stop("method 'lynx' is defunct", domain = NA))
  if (status) 
    warning("download had nonzero exit status")
  invisible(status)
}