R/utils.R

Defines functions aemet_hlp_sf aemet_hlp_guess

# Internal helpers functions: This functions are not exported

#' Guess formats
#'
#' @param tbl a tibble
#' @param preserve vector of names to preserve
#' @return a `tibble`.
#' @noRd
aemet_hlp_guess <-
  function(tbl,
           preserve = "",
           dec_mark = ",",
           group_mark = "") {
    for (i in names(tbl)) {
      if (class(tbl[[i]])[1] == "character" && !(i %in% preserve)) {
        tbl[i] <-
          readr::parse_guess(
            tbl[[i]],
            locale = readr::locale(
              decimal_mark = dec_mark,
              grouping_mark = group_mark
            ),
            na = "-"
          )
      }
    }
    return(tbl)
  }


#' Convert to sf objects (maps)
#'
#' @param tbl a tibble
#' @param lat,lon latitude and longitude fiels
#' @param verbose TRUE/FALSE
#' @return a tibble or a `sf` object
#' @noRd
aemet_hlp_sf <- function(tbl, lat, lon, verbose = FALSE) {
  # Check if sf is installed
  if (!requireNamespace("sf", quietly = TRUE)) {
    message("\n\npackage sf required for spatial conversion, please install it first")
    message("\nReturnig a tibble")
    return(tbl)
  }

  if (lat %in% names(tbl) && lon %in% names(tbl)) {
    if (any(is.na(tbl[[lat]]) || any(is.na(tbl[[lon]])))) {
      message("Found NA coordinates. Returning a tibble")
      return(tbl)
    }

    if (verbose) {
      message("Converting to spatial object")
    }


    out <-
      sf::st_as_sf(tbl,
        coords = c(lon, lat),
        crs = sf::st_crs(4326)
      )
    if (verbose) {
      message("spatial conversion succesful")
    }
    return(out)
  } else {
    message("lat/lon columns not found. Returning a tibble")
    return(tbl)
  }
}

Try the climaemet package in your browser

Any scripts or data that you put into this service are public.

climaemet documentation built on March 18, 2022, 7:01 p.m.