R/read.R

Defines functions read_fdb_csv

Documented in read_fdb_csv

#' Read CSV file generated by FDB
#'
#' Read a CSV file generated by Ferjedatabanken.
#'
#' @param file Path to file. See [readr::read_file()] for details.
#' @param total Extract total values.
#' @param unparsed Return unparsed data frame.
#'
#' @return A data frame.
#' @export
read_fdb_csv <- function(file, total = FALSE, unparsed = FALSE) {
  csv_pages <- readr::read_file(file, readr::locale(encoding = "latin1")) %>%
    stringr::str_split("\n[^\n]*Side \\d[^\n]*\n") %>%
    purrr::flatten_chr()

  d <- purrr::map_dfr(csv_pages, parse_csv_page)

  if (unparsed) return(d)

  type <- unique(d$type)
  if ("subtype" %in% names(d)) {
    subtype <- unique(d$subtype)
  } else {
    subtype <- NULL
  }

  if (stringr::str_detect(type, "^Variasjonskurver")) {
    if (identical(subtype, "D\u00f8gnvariasjon")) {
      d <- parse_variasjonskurver_dognvariasjon(d, total)
    } else if (identical(subtype, "Ukesvariasjon")) {
      if (total) warning("Parameter \"total\" not implemented.")
      d <- parse_variasjonskurver_ukesvariasjon(d)
    } else if (identical(subtype, "\u00c5rsvariasjon")) {
      d <- parse_variasjonskurver_aarsvariasjon(d, total)
    } else {
      stop("Unknown error.")
    }
  } else if (identical(type, "Trafikkindeks") ||
             identical(type, "Begrenset trafikkindeks")) {
    if (identical(subtype, "\u00c5rsindeks")) {
      d <- parse_trafikkindeks_aarsindeks(d, total)
    } else if (identical(subtype, "Kvartalsindeks")) {
      d <- parse_trafikkindeks_kvartalsindeks(d, total)
    } else if (identical(subtype, "Siste 12 m\u00e5neder")) {
      d <- parse_trafikkindeks_siste_12_maaneder(d, total)
    } else {
      stop("Unknown error.")
    }
  } else if (identical(type, "Trafikkverdier")) {
    if (total) warning("Parameter \"total\" ignored.")
    d <- parse_trafikkverdier(d)
  } else if (identical(type, "Produksjon")) {
    d <- parse_produksjon(d, total)
  } else if (stringr::str_detect(type, "^Sonefordeling")) {
    d <- parse_sonefordeling(d, total)
  } else {
    warning("Unimplemented file type. Returning unparsed data frame.")
  }

  d
}
hmalmedal/readfdb documentation built on Sept. 15, 2019, 7:19 p.m.