R/utils.R

Defines functions aemet_hlp_sf aemet_hlp_guess

# Internal helper functions: these functions are not exported

#' Guess formats
#'
#' @param tbl a [tibble][tibble::tbl_df]
#' @param preserve vector of names to preserve
#' @return A [tibble][tibble::tbl_df]
#' @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 = "-"
      )
    }
  }
  tbl
}

#' Convert to sf objects (maps)
#'
#' @param tbl a [tibble][tibble::tbl_df]
#' @param lat,lon latitude and longitude fields
#' @param verbose TRUE/FALSE
#' @return A [tibble][tibble::tbl_df] or a \CRANpkg{sf} object
#' @noRd
aemet_hlp_sf <- function(tbl, lat, lon, verbose = FALSE) {
  # Check if sf is installed
  # nocov start
  if (!requireNamespace("sf", quietly = TRUE)) {
    cli::cli_alert_warning(c(
      "Package {.pkg sf} required for spatial conversion, ",
      "please install it first."
    ))
    cli::cli_alert_info("Returning a {.cls tibble}.")
    return(tbl)
  }
  # nocov end
  if (lat %in% names(tbl) && lon %in% names(tbl)) {
    if (anyNA(tbl[[lat]]) || anyNA(tbl[[lon]])) {
      cli::cli_alert_warning(
        "Found {.val NA} coordinates. Returning a {.cls tibble}."
      )
      return(tbl)
    }

    if (verbose) {
      cli::cli_alert_info("Converting to spatial object with {.pkg sf}.")
    }

    out <- sf::st_as_sf(tbl, coords = c(lon, lat), crs = sf::st_crs(4326))
    if (verbose) {
      cli::cli_alert_success("Spatial conversion successful")
    }
    out
  } else {
    cli::cli_alert_info(
      "{.arg lat/lon} columns not found. Returning a {.cls tibble}."
    )
    tbl
  }
}

# Default station for metadata
default_station <- "9434"

Try the climaemet package in your browser

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

climaemet documentation built on March 24, 2026, 1:06 a.m.