R/datasets.R

Defines functions load_dataset get_dataset_info list_census load_metadata

Documented in list_census load_dataset

#' Charger les metadonnees des datasets
#' @keywords internal
load_metadata <- function() {
  # Chemin vers le fichier interne au package
  meta_path <- system.file("extdata", "metadata.json", package = "sencensus")
  if (meta_path == "") {
    stop("Fichier metadata.json introuvable dans le package.")
  }
  jsonlite::fromJSON(meta_path, simplifyDataFrame = TRUE)
}

#' Lister les recensements disponibles / List available censuses
#'
#' @return A data.frame containing the list of available census datasets with columns 'id', 'year', 'name', and 'description'.
#' @export
#' @examples
#' list_census()
list_census <- function() {
  meta <- load_metadata()
  if (nrow(meta) > 0) {
    return(meta[, c("id", "year", "name", "description")])
  }
  return(meta)
}

#' Obtenir les infos d'un dataset specifique
#' @keywords internal
get_dataset_info <- function(dataset_id) {
  meta <- load_metadata()
  # Filtre par id exact ou par year
  match <- meta[meta$id == dataset_id | meta$year == dataset_id, ]
  if (nrow(match) == 0) {
    stop(paste("Aucun dataset trouve pour l'identifiant:", dataset_id))
  }
  return(match[1, ])
}

#' Charger un dataset dans R / Load a dataset into R
#'
#' @param dataset_id L'identifiant (ex: 2013, "projection", "coordonnées") / Dataset identifier (e.g., 2013, "projection")
#' @return A data.frame (or tibble) containing the census dataset loaded into memory.
#' @export
#' @examples
#' \donttest{
#' download("projection")
#' df <- load_dataset("projection")
#' head(df)
#' }
load_dataset <- function(dataset_id) {
  info <- get_dataset_info(dataset_id)
  filename <- info$file_name
  filepath <- get_cached_file_path(filename)
  
  if (!file.exists(filepath)) {
    stop(sprintf("Le fichier %s n'a pas ete trouve. Veuillez executer sencensusR::download('%s') d'abord.", filename, dataset_id))
  }
  
  message(sprintf("Chargement des donnees pour %s depuis le cache...", dataset_id))
  
  if (info$format == "csv") {
    # Test tryCatch pour readr
    res <- tryCatch({
      readr::read_csv(filepath, show_col_types = FALSE)
    }, error = function(e) {
      message("Avertissement: read_csv a echoue, essai avec sep=';'")
      readr::read_csv2(filepath, show_col_types = FALSE)
    })
    return(res)
  } else if (info$format %in% c("xls", "xlsx")) {
    return(readxl::read_excel(filepath))
  } else {
    stop(sprintf("Format non supporte: %s", info$format))
  }
}

Try the sencensus package in your browser

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

sencensus documentation built on Sept. 26, 2026, 5:06 p.m.