rspatial / geodata

download geographic data
GNU General Public License v3.0
147 stars 15 forks source link

It's possible create the worldclim_hist function? #69

Open denis-or opened 3 months ago

denis-or commented 3 months ago

Hello.

I'm currently using the Climate Research Unit's climate time series datasets and noticed that there is no function in geodata. So, here's my suggestion:

References: https://www.worldclim.org/data/monthlywth.html https://crudata.uea.ac.uk/cru/data/hrg/

worldclim_hist <- function(var, res, path, time, version="4.06", ...) {

  res <- as.character(res)
  version <- as.character(version)
  stopifnot(res %in% c("2.5", "5", "10"))
  stopifnot(var %in% c("tmin", "tmax", "prec"))
  stopifnot(version %in% c("4.06"))
  stopifnot(time %in% c("1960-1969", "1970-1979", "1980-1989", "1990-1999", "2000-2009", "2010-2019"))

  fres <- paste0(res, "m")

  path <- file.path(path, paste0("wc2.1_cruts", version, "_", fres, "/"))
  dir.create(path, showWarnings=FALSE)
  zip <- paste0("wc2.1_cruts", version, "_", fres, "_", var, "_", time, ".zip")

  ff <- paste0("wc2.1_cruts", version, "_", fres, "_", var, "_", time, ".tif")

  pzip <- file.path(path, zip)
  ff <- file.path(path, ff)
  if (!all(file.exists(ff))) {
    turl <- .wc_url(paste0("hist/cts", version, "/", fres, "/", zip))
    if (is.null(turl)) return(NULL)

    if (!.downloadDirect(turl, pzip, ...)) return(NULL)
    fz <- try(utils::unzip(pzip, exdir=path), silent=TRUE)
    try(file.remove(pzip), silent=TRUE)
    if (inherits(fz, "try-error")) {
      message("download failed")
      return(NULL)
    }
  }
  rast(ff)
}