R/mopex_data_download.R

Defines functions data_download

Documented in data_download

#' Download multiple datasets from Mopex website as one combined dataset
#'
#' @param id the datasets we want to download
#' @param save whether we want to save the combined datasets
#' @param path where we want to save the file
#' @param file_name what name we want to give to the file
#'
#' @return
#' @export
#' @examples
#' \dontrun{
#' data_download(id = '01048000', save = FALSE)
#' }


data_download <- function(id,
                          save = FALSE,
                          path = NULL,
                          file_name = NULL) {

  dta <- lapply(
    X = id,
    FUN = function(x) {

      message(paste("downloading", x))

      dl <- read.fwf(file = paste0("https://hydrology.nws.noaa.gov/pub/gcip/mopex/US_Data/Us_438_Daily/",
                                   x,
                                   ".dly"),
                     widths = c(8, rep(x = 10,
                                       times = 5)),
                     col.names = c("DTM", "P", "E", "Q", "Tmax", "Tmin"))

      dl$DTM <- as.Date(x = gsub(pattern = " ",
                                 replacement = "0",
                                 x = dl$DTM),
                        format = "%Y%m%d")
      dl$ID <- x

      dl
    }
  )

  dta_bind <- do.call(what = rbind,
                      args = dta)
  dta_bind$ID <- as.factor(x = dta_bind$ID)

  if (save) {

    if (any(is.null(x = path),
            is.null(x = file_name))) {

      stop("path or filename was not supplied")
    }

    write.csv(x = dta_bind,
              file = file.path(path, file_name))

    if (file.exists(file.path(path, file_name))) {

      message("file created succesfully")
    }
  }

  dta_bind
}
veravavan/RPackage documentation built on Dec. 23, 2021, 3:03 p.m.