Skip to content

Instantly share code, notes, and snippets.

@jmclawson
Last active January 13, 2023 17:50
Show Gist options
  • Save jmclawson/65899e2de6bfee692b08141a98422240 to your computer and use it in GitHub Desktop.
Save jmclawson/65899e2de6bfee692b08141a98422240 to your computer and use it in GitHub Desktop.
Downloads a url if it doesn't already exist locally
get_if_needed <- function(
# Url to be downloaded, necessary
url,
# destination filename (optional)
filename = NULL,
# destination directory (optional)
destdir = "data"
) {
# If `filename` parameter is not set, it defaults to online file name.
if(is.null(filename)){
the_filename <- url |> str_extract("[a-z A-Z 0-9 \\- _]+[.]{1,1}+[a-zA-Z]{1,4}$")
} else {
the_filename <- filename
}
# The `destdir` directory will be created if necessary
if(!dir.exists(destdir)){
dir.create(destdir)
}
filepath <- file.path(destdir, the_filename)
if(!file.exists(filepath)) {
download.file(url, destfile = filepath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment