R/gu_routes_shapes.R

Defines functions gu_routes_shapes

Documented in gu_routes_shapes

#' Routes shapes retriever
#'
#' Returns a sf object with the GTFS' routes shapes.
#'
#' @param gtfs The path to the GTFS file from which you want to retrieve the
#'   routes shapes.
#' @param crs The desired CRS of the sf object (something suitable as input to
#'   \code{\link[sf]{st_crs}}).
#' @param sep The delimiter used to separate each entry in the txt files within
#'   the GTFS. Defaults to \code{","}.
#' @return A sf with \code{shape_id} and \code{geom} columns.
#' @examples
#' gu_routes_shapes(gtfs = "./data/rio_gtfs.zip", crs = 4674, sep = ";")

gu_routes_shapes <- function(gtfs, crs, sep = ",") {

  shapes <- utils::read.csv(
    unz(gtfs, "shapes.txt"),
    sep = sep,
    stringsAsFactors = FALSE
  )

  shapes <- dplyr::group_by(shapes, shape_id)
  shapes <- dplyr::summarise(shapes, coords = list(matrix(c(shape_pt_lon, shape_pt_lat), ncol = 2)))

  sf_column <- sf::st_multilinestring(shapes$coords)
  sf_column <- sf::st_sfc(sf_column)
  sf_column <- sf::st_cast(sf_column, "LINESTRING")

  shapes <- dplyr::select(shapes, -coords)
  shapes <- sf::st_sf(shapes, geom = sf_column, crs = crs)

  return(shapes)

}
dhersz/gtfsutils documentation built on Aug. 15, 2020, 12:38 a.m.