Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:General Transit Feed Specification (GTFS) Editing and AnalysingTools
Version:1.4.0
Description:Utility functions to read, manipulate, analyse and write transit feeds in the General Transit Feed Specification (GTFS) data format.
License:MIT + file LICENSE
URL:https://ipeagit.github.io/gtfstools/,https://github.com/ipeaGIT/gtfstools
BugReports:https://github.com/ipeaGIT/gtfstools/issues
Depends:R (≥ 2.10)
Imports:checkmate, cli, curl, data.table, gtfsio (≥ 1.0.0),parallelly, processx, sf, sfheaders, units, utils, zip
Suggests:covr, ggplot2, jsonlite, knitr, rmarkdown, testthat (≥3.0.0)
VignetteBuilder:knitr
Config/testthat/edition:3
Encoding:UTF-8
NeedsCompilation:yes
RoxygenNote:7.3.2
LinkingTo:cpp11
Packaged:2025-01-08 14:26:22 UTC; R3422553
Author:Daniel HerszenhutORCID iD [aut, cre], Rafael H. M. PereiraORCID iD [aut], Pedro R. AndradeORCID iD [aut], Joao BazzoORCID iD [aut], Mark Padgham [ctb], Marcus SaraivaORCID iD [ctb], Ipea - Institute for Applied Economic Research [cph, fnd]
Maintainer:Daniel Herszenhut <dhersz@gmail.com>
Repository:CRAN
Date/Publication:2025-01-09 00:40:02 UTC

gtfstools: General Transit Feed Specification (GTFS) Editing and AnalysingTools

Description

Utility functions to read, manipulate, analyse and write transit feeds in theGeneral Transit Feed Specification (GTFS) data format.

Usage

Please check the vignettes for more on the package usage:

Author(s)

Maintainer: Daniel Herszenhutdhersz@gmail.com (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Coerce lists and GTFS objects from other packages into gtfstools-compatibleGTFS objects

Description

Coerces an existing object, such as alist or a GTFS object created fromother packages ({tidytransit} and{gtfsio}, for example) into agtfstools-compatible GTFS object - i.e. one whose internal tables arerepresented withdata.tables and whose fields are formatted like the fieldsof a feed read withread_gtfs().

as_dt_gtfs() is an S3 generic, with methods for:

Usage

as_dt_gtfs(gtfs, ...)## S3 method for class 'tidygtfs'as_dt_gtfs(gtfs, calculate_distance = TRUE, ...)## S3 method for class 'gtfs'as_dt_gtfs(gtfs, ...)## S3 method for class 'list'as_dt_gtfs(gtfs, ...)

Arguments

gtfs

The object that should be coerced to adt_gtfs.

...

Ignored.

calculate_distance

A logical. Passed toconvert_sf_to_shapes(),which only affects the output when the object to be converted includes ashapes element. Controls whether this function, used to convert a⁠LINESTRING sf⁠ into a GTFSshapes table, should calculate and populatetheshape_dist_traveled column. This column is used to describe thedistance along the shape from each one of its points to its first point.Defaults toTRUE.

Value

Adt_gtfs GTFS object.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfsio_gtfs <- gtfsio::import_gtfs(data_path)class(gtfsio_gtfs)gtfstools_gtfs <- as_dt_gtfs(gtfsio_gtfs)class(gtfstools_gtfs)gtfs_like_list <- unclass(gtfsio_gtfs)class(gtfs_like_list)gtfstools_gtfs <- as_dt_gtfs(gtfs_like_list)class(gtfstools_gtfs)

Convert a standards-compliant GTFS into a gtfstools' GTFS

Description

Converts a standards-compliant GTFS into a gtfstools' GTFS (i.e. one in whichdate fields are Date objects, not integers).

Usage

convert_from_standard(gtfs)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

Value

The GTFS object passed to thegtfs parameter, after converting therelevant fields.


Convert a simple feature object into ashapes table

Description

Converts a⁠LINESTRING sf⁠ object into a GTFSshapes table.

Usage

convert_sf_to_shapes(sf_shapes, shape_id = NULL, calculate_distance = TRUE)

Arguments

sf_shapes

A⁠LINESTRING sf⁠ associating eachshape_ids to ageometry. This object must use CRS WGS 84 (EPSG code 4326).

shape_id

A character vector specifying theshape_ids to beconverted. IfNULL (the default), all shapes are converted.

calculate_distance

A logical. Whether to calculate and populate theshape_dist_traveled column. This column is used to describe the distancealong the shape from each one of its points to its first point. Defaults toTRUE.

Value

Adata.table representing a GTFSshapes table.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)# first converting existing shapes table into a sf objectshapes_sf <- convert_shapes_to_sf(gtfs)head(shapes_sf)# by default converts all shapesresult <- convert_sf_to_shapes(shapes_sf)result# shape_id argument controls which shapes are convertedresult <- convert_sf_to_shapes(shapes_sf, shape_id = c("17846", "17847"))result# calculate_distance argument controls whether to calculate# shape_dist_traveled or notresult <- convert_sf_to_shapes(shapes_sf, calculate_distance = TRUE)result

Convertshapes table to simple feature object

Description

Converts theshapes table to a⁠LINESTRING sf⁠ object.

Usage

convert_shapes_to_sf(gtfs, shape_id = NULL, crs = 4326, sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

shape_id

A character vector including theshape_ids to be converted.IfNULL (the default), all shapes are converted.

crs

The CRS of the resulting object, either as an EPSG code or as ancrs object. Defaults to 4326 (WGS 84).

sort_sequence

A logical. Whether to sort shapes byshape_pt_sequence. Defaults toFALSE, otherwise spec-compliant feeds,in which shape points are already ordered byshape_pt_sequence, would bepenalized through longer processing times. Shapes generated from unorderedsequences do not correctly depict the real life trip shapes.

Value

A⁠LINESTRING sf⁠ object.

Examples

# read gtfsdata_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)shapes_sf <- convert_shapes_to_sf(gtfs)head(shapes_sf)shapes_sf <- convert_shapes_to_sf(gtfs, shape_id = "17846")shapes_sf

Convertstops table to simple feature object

Description

Converts thestops table to a⁠POINT sf⁠ object.

Usage

convert_stops_to_sf(gtfs, stop_id = NULL, crs = 4326)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

stop_id

A character vector including thestop_ids to be converted.IfNULL (the default), all stops are converted.

crs

The CRS of the resulting object, either as an EPSG code or as ancrs object. Defaults to 4326 (WGS 84).

Value

A⁠POINT sf⁠ object.

Examples

# read gtfsdata_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)stops_sf <- convert_stops_to_sf(gtfs)head(stops_sf)stops_sf <- convert_stops_to_sf(gtfs, stop_id = "18848")stops_sf

Convert time fields to seconds after midnight

Description

Convertsstop_times' andfrequencies' fields in the "HH:MM:SS" format toseconds after midnight. Instead of overwritting the existing fields, createsnew fields with the⁠_secs⁠ suffix.

Usage

convert_time_to_seconds(gtfs, file = NULL, by_reference = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

file

A character vector, specifying the file whose fields should beconverted. IfNULL (the default), the function attempts to convert thetimes from both files, but only raises an error if none of them exist.

by_reference

Whether to update the tables by reference. Defaults toFALSE.

Value

Ifby_reference isFALSE, returns a GTFS object with additionaltime in seconds columns (identified by a⁠_secs⁠ suffix). Else, returns aGTFS object invisibly (please note that in such case the original GTFS objectis altered).

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)# by default converts both 'stop_times' and 'frequencies' timesconverted_gtfs <- convert_time_to_seconds(gtfs)head(converted_gtfs$stop_times)head(converted_gtfs$frequencies)# choose which table to convert with 'file'converted_gtfs <- convert_time_to_seconds(gtfs, file = "frequencies")head(converted_gtfs$stop_times)head(converted_gtfs$frequencies)# original gtfs remained unchanged, as seen with the frequencies table above# change original object without creating a copy with 'by_reference = TRUE'convert_time_to_seconds(gtfs, by_reference = TRUE)head(gtfs$stop_times)head(gtfs$frequencies)

Convert a gtfstools' GTFS into a standards-compliant GTFS

Description

Converts a gtfstools' GTFS into a standards-compliant GTFS (i.e. date fieldsare converted from Date to integer).

Usage

convert_to_standard(gtfs)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

Value

The GTFS object passed to thegtfs parameter, after converting therelevant fields.


Make a GTFS copy with a field of a different class

Description

Creates a copy of a GTFS object while changing the class of a given field.Used for testing.

Usage

copy_gtfs_diff_field_class(gtfs, file, field, class)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

file

File whose field must have the class changed.

field

Field to have the class changed.

class

The desired class.

Value

A GTFS object with the field of desired class.


Make a GTFS copy without a given field from a given file

Description

Creates a copy of a GTFS object without a given field from a given file. Usedfor testing.

Usage

copy_gtfs_without_field(gtfs, file, field)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

file

File from which the field must be removed.

field

Field to be removed.

Value

A GTFS object without the given field.


Make a GTFS copy without a given file

Description

Creates a copy of a GTFS object without a given file. Used for testing.

Usage

copy_gtfs_without_file(gtfs, file)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

file

File to be removed.

Value

A GTFS object without the given file.


Convert a Date vector into an integer vector

Description

Convert a Date vector into an integer vector

Usage

date_to_integer(field)

Download MobilityData's GTFS validator

Description

Downloads MobilityData's command line tool to validate GTFS feeds.

Usage

download_validator(path, version = "latest", force = FALSE, quiet = TRUE)

Arguments

path

A string. The directory where the validator should be saved to.

version

A string. The version of the validator that should bedownloaded. Defaults to"latest", but accepts version numbers as strings(i.e. to download version v6.0.0 please enter"6.0.0"). Please checkMobilityData/gtfs-validator releases for thefull set of available versions.

force

A logical. Whether to overwrite a previously downloadedvalidator inpath. Defaults toFALSE.

quiet

A logical. Whether to hide log messages and progress bars.Defaults toTRUE.

Value

Invisibly returns the normalized path to the downloaded validator.

See Also

Other validation:validate_gtfs()

Examples

path <- tempdir()download_validator(path)# specifying a specific versiondownload_validator(path, version = "6.0.0")

Filter GTFS object byagency_id

Description

Filters a GTFS object byagency_ids, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_agency_id(gtfs, agency_id, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

agency_id

A character vector. Theagency_ids used to filter thedata.

keep

A logical. Whether the entries related to the specifiedagency_ids should be kept or dropped (defaults toTRUE, which keeps theentries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/ber_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)agency_id <- "92"object.size(gtfs)# keeps entries related to passed agency_idsmaller_gtfs <- filter_by_agency_id(gtfs, agency_id)object.size(smaller_gtfs)# drops entries related to passed agency_idsmaller_gtfs <- filter_by_agency_id(gtfs, agency_id, keep = FALSE)object.size(smaller_gtfs)

Filter GTFS object byroute_id

Description

Filters a GTFS object byroute_ids, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_route_id(gtfs, route_id, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

route_id

A character vector. Theroute_ids used to filter the data.

keep

A logical. Whether the entries related to the specifiedroute_ids should be kept or dropped (defaults toTRUE, which keeps theentries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)route_ids <- c("6450-51", "CPTM L11")object.size(gtfs)# keeps entries related to passed route_idssmaller_gtfs <- filter_by_route_id(gtfs, route_ids)object.size(smaller_gtfs)# drops entries related to passed route_idssmaller_gtfs <- filter_by_route_id(gtfs, route_ids, keep = FALSE)object.size(smaller_gtfs)

Filter GTFS object byroute_type (transport mode)

Description

Filters a GTFS object byroute_types, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_route_type(gtfs, route_type, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

route_type

An integer vector. Theroute_types used to filter thedata.

keep

A logical. Whether the entries related to the specifiedroute_types should be kept or dropped (defaults toTRUE, which keepsthe entries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

Route types

Valid options include the route types listed in the GTFS Schedulespecification and in the Google Transit implementation. The types specifiedin the GTFS Schedule specification are:

The types defined in Google Transit's extension are listed below, includingsome examples (not available for all types):

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

# read gtfsdata_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)object.size(gtfs)# keeps entries related to passed route_typessmaller_gtfs <- filter_by_route_type(gtfs, route_type = 1)object.size(smaller_gtfs)# drops entries related to passed route_typessmaller_gtfs <- filter_by_route_type(gtfs, route_type = 1, keep = FALSE)object.size(smaller_gtfs)

Filter GTFS object byservice_id

Description

Filters a GTFS object byservice_ids, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_service_id(gtfs, service_id, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

service_id

A character vector. Theservice_ids used to filter thedata.

keep

A logical. Whether the entries related to the specifiedservice_ids should be kept or dropped (defaults toTRUE, which keeps theentries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)service_ids <- c("USD", "U__")object.size(gtfs)# keeps entries related to the specified service_idssmaller_gtfs <- filter_by_service_id(gtfs, service_ids)object.size(smaller_gtfs)# drops entries related to the specified service_idssmaller_gtfs <- filter_by_service_id(gtfs, service_ids, keep = FALSE)object.size(smaller_gtfs)

Filter a GTFS object using a⁠simple features⁠ object (deprecated)

Description

This function has been deprecated as of the current package version and willbe completely removed from version 2.0.0 onward. Please usefilter_by_spatial_extent() instead.

Filters a GTFS object using the geometry of ansf object, keeping (ordropping) entries related to shapes and trips selected through a spatialoperation.

Usage

filter_by_sf(gtfs, geom, spatial_operation = sf::st_intersects, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

geom

Ansf object. Describes the geometry used to filter the data.

spatial_operation

A spatial operation function from the set ofoptions listed ingeos_binary_pred (check theDE-I9M Wikipedia entry for thedefinition of each function). Defaults tosf::st_intersects, which testsif the shapes and trips have ANY intersection with the object specified ingeom. Please note thatgeom is passed as thex argument of thesefunctions.

keep

A logical. Whether the entries related to the shapes and tripsthat cross through the given geometry should be kept or dropped (defaultstoTRUE, which keeps the entries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)shape_id <- "68962"shape_sf <- convert_shapes_to_sf(gtfs, shape_id)bbox <- sf::st_bbox(shape_sf)object.size(gtfs)# keeps entries that intersect with the specified polygonsmaller_gtfs <- filter_by_sf(gtfs, bbox)object.size(smaller_gtfs)# drops entries that intersect with the specified polygonsmaller_gtfs <- filter_by_sf(gtfs, bbox, keep = FALSE)object.size(smaller_gtfs)# uses a different function to filter the gtfssmaller_gtfs <- filter_by_sf(gtfs, bbox, spatial_operation = sf::st_contains)object.size(smaller_gtfs)

Filter GTFS object byshape_id

Description

Filters a GTFS object byshape_ids, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_shape_id(gtfs, shape_id, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

shape_id

A character vector. Theshape_ids used to filter the data.

keep

A logical. Whether the entries related to the specifiedshape_ids should be kept or dropped (defaults toTRUE, which keeps theentries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)shape_ids <- c("17846", "68962")object.size(gtfs)# keeps entries related to passed shape_idssmaller_gtfs <- filter_by_shape_id(gtfs, shape_ids)object.size(smaller_gtfs)# drops entries related to passed shape_idssmaller_gtfs <- filter_by_shape_id(gtfs, shape_ids, keep = FALSE)object.size(smaller_gtfs)

Filter a GTFS object using a spatial extent

Description

Filters a GTFS object using a spatial extent (passed as ansf object),keeping (or dropping) entries related to shapes and trips whose geometriesare selected through a specified spatial operation.

Usage

filter_by_spatial_extent(  gtfs,  geom,  spatial_operation = sf::st_intersects,  keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

geom

Ansf object. Describes the spatial extent used to filter thedata.

spatial_operation

A spatial operation function from the set ofoptions listed ingeos_binary_pred (check theDE-I9M Wikipedia entry for thedefinition of each function). Defaults tosf::st_intersects, whichtests if the shapes and trips have ANY intersection with the objectspecified ingeom. Please note thatgeom is passed as thex argumentof these functions.

keep

A logical. Whether the entries related to the shapes and tripsselected by the given spatial operation should be kept or dropped (defaultstoTRUE, which keeps the entries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)shape_id <- "68962"shape_sf <- convert_shapes_to_sf(gtfs, shape_id)bbox <- sf::st_bbox(shape_sf)object.size(gtfs)# keeps entries that intersect with the specified polygonsmaller_gtfs <- filter_by_spatial_extent(gtfs, bbox)object.size(smaller_gtfs)# drops entries that intersect with the specified polygonsmaller_gtfs <- filter_by_spatial_extent(gtfs, bbox, keep = FALSE)object.size(smaller_gtfs)# uses a different function to filter the gtfssmaller_gtfs <- filter_by_spatial_extent(  gtfs,  bbox,  spatial_operation = sf::st_contains)object.size(smaller_gtfs)

Filter GTFS object bystop_id

Description

Filters a GTFS object bystop_ids, keeping (or dropping) relevant entriesin each file.

Usage

filter_by_stop_id(  gtfs,  stop_id,  keep = TRUE,  include_children = TRUE,  include_parents = keep,  full_trips = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

stop_id

A character vector. Thestop_ids used to filter the data.

keep

A logical. Whether the entries related to thetrip_ids thatpasses through the specifiedstop_ids should be kept or dropped (defaultstoTRUE, which keeps the entries).

include_children

A logical. Whether the filtered output shouldkeep/drop children stops of those specified instop_id. Defaults toTRUE - i.e. by default children stops are kept if their parents are keptand dropped if their parents are dropped.

include_parents

A logical. Whether the filtered output shouldkeep/drop parent stations of those specified instop_id. Defaults tothe same value ofkeep - i.e. by default parent stations are kept bothwhen their children are kept and dropped, because they can be parents ofmultiple stops that are not necessarily dropped, even if their sibling are.

full_trips

A logical. Whether to keep all stops that compose tripsthat pass through the stops specified instop_id. Defaults toTRUE, inorder to preserve the behavior of the function in versions 1.2.0 and below.Please note that whenTRUE, the resultant filtered feed may contain morestops than the ones specified instop_id to preserve the integrity of thetrips. IMPORTANT: usingfull_trips = TRUE is flagged as deprecated as ofversion 1.3.0 and this parameter will default toFALSE from version 2.0.0onward.

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_time_of_day(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)stop_ids <- c("18848", "940004157")object.size(gtfs)# keeps entries related to trips that pass through specified stop_idssmaller_gtfs <- filter_by_stop_id(gtfs, stop_ids, full_trips = FALSE)object.size(smaller_gtfs)# drops entries related to trips that pass through specified stop_idssmaller_gtfs <- filter_by_stop_id(  gtfs,  stop_ids,  keep = FALSE,  full_trips = FALSE)object.size(smaller_gtfs)# the old behavior of filtering trips that contained the specified stops has# been deprecatedinvisible(filter_by_stop_id(gtfs, stop_ids, full_trips = TRUE))

Filter GTFS object by time of day

Description

Filters a GTFS object by time of day, keeping (or dropping) the relevantentries in each file. Please see the details section for more information onhow this function filters thefrequencies andstop_times tables, as wellas how it handlesstop_times tables that contain trips with some emptydeparture and arrival times.

Usage

filter_by_time_of_day(  gtfs,  from,  to,  keep = TRUE,  full_trips = FALSE,  update_frequencies = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

from

A string. The starting point of the time of day, in the"HH:MM:SS" format.

to

A string. The ending point of the time of day, in the "HH:MM:SS"format.

keep

A logical. Whether the entries related to the specified time ofday should be kept or dropped (defaults toTRUE, which keeps the entries).

full_trips

A logical. Whether trips should be treated as immutableblocks or each of its stops should be considered separately when filteringthestop_times table (defaults toFALSE, which considers each stopindividually). Please check the details section for more information on howthis parameter changes the function behaviour.

update_frequencies

A logical. Whether thefrequencies table shouldhave itsstart_time andend_time fields updated to fit inside/outside thespecified time of day (defaults toFALSE, which doesn't update the fields).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

Details

When filtering thefrequencies table,filter_by_time_of_day() respectstheexact_times field. This field indicates whether the service follows afixed schedule throughout the day or not. If it's 0 (or if it's notpresent), the service does not follow a fixed schedule. Instead, theoperators try to maintain the listed headways. In such cases, ifupdate_frequencies isTRUE we just updatestart_time andend_time tothe appropriate value offrom orto (which of this value is used dependsonkeep).

Ifexact_times is 1, however, operators try to strictly adhere to the starttimes and headway. As a result, when updating thestart_time field we needto follow the listed headway. For example, take a trip that has its starttime listed as 06:00:00, its end time listed as 08:00:00 and its headwaylisted as 300 secs (5 minutes). If you decide to filter the feed to keep thetime of day between 06:32:00 and 08:00:00 while updatingfrequencies, thestart_time field must be updated to 06:35:00 in order to preserve thecorrect departure times of this trips, instead of simply updating it to06:32:00.

Another things to keep an eye on when filtering thefrequencies table isthat the correspondingstop_times entries of trips listed in thefrequencies table should not be filtered, even if their departure andarrival times fall outside the specified time of day. This is because thestop_times entries offrequencies' trips are just templates that describehow long a segment between two stops takes, so the departure and arrivaltimes listed there do not actually represent the actual departure andarrival times seen in practice. Taking the same example listed above, thecorrespondingstop_times entries of that trip could describe a departurefrom the first stop at 12:00:00 and an arrival at the second stop at12:03:00. That doesn't mean the trip will actually leave and arrive at thestops at these times, but rather that it takes 3 minutes to get from thefirst to the second stop. So when the trip departs from the first stop at06:35:00, it will get to the second at 06:38:00.

When filtering thestop_times table, a few other details should beobserved. First, one could wish to filter a GTFS object in order to keep alltrips that cross a given time of day, whereas others may want to keep onlythe specific entries that fall inside the specified time of day. Forexample, take a trip that leaves the first stop at 06:30:00, gets to thesecond at 06:35:00 and then gets to the third at 06:45:00. When filtering tokeep entire trips that cross the time of day between 06:30:00 and 06:40:00,all three stops will have to be kept. If, however, you want to keep only theentries that fall within the specified time of day, only the first twoshould be kept. To control such behaviour you need to set thefull_tripsparameter. When it'sTRUE, the function behaves like the first case, andwhen it'sFALSE, like the second.

When usingfull_trips in conjunction withkeep, please note how theirbehaviour stack. When both areTRUE, trips are always fully kept. Whenkeep isFALSE, however, trips are fully dropped, even if some of theirstops are visited outside the specified time of day.

Finally, please note that many GTFS feeds may containstop_times entrieswith empty departure and arrival times. In such cases, filtering by time ofday withfull_trips asFALSE will drop the entries with empty times.Please setfull_trips toTRUE to preserve these entries.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_trip_id(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)# taking a look at the original frequencies and stop_timeshead(gtfs$frequencies)head(gtfs$stop_times)smaller_gtfs <- filter_by_time_of_day(gtfs, "05:00:00", "06:00:00")# filter_by_time_of_day filters the frequencies table but doesn't filter the# stop_times table because they're just templateshead(smaller_gtfs$frequencies)head(smaller_gtfs$stop_times)# frequencies entries can be adjusted using update_frequencies = TRUEsmaller_gtfs <- filter_by_time_of_day(  gtfs,  "05:30:00",  "06:00:00",  update_frequencies = TRUE)head(smaller_gtfs$frequencies)# when keep = FALSE, the behaviour of the function in general, and of# update_frequencies in particular, is a bit differentsmaller_gtfs <- filter_by_time_of_day(  gtfs,  "05:30:00",  "06:00:00",  keep = FALSE,  update_frequencies = TRUE)head(smaller_gtfs$frequencies)# let's remove the frequencies table to check the behaviour of full_tripsgtfs$frequencies <- NULLsmaller_gtfs <- filter_by_time_of_day(  gtfs,  "05:30:00",  "06:00:00")head(smaller_gtfs$stop_times)smaller_gtfs <- filter_by_time_of_day(  gtfs,  "05:30:00",  "06:00:00",  full_trips = TRUE)head(smaller_gtfs$stop_times)

Filter GTFS object bytrip_id

Description

Filters a GTFS object bytrip_ids, keeping (or dropping) the relevantentries in each file.

Usage

filter_by_trip_id(gtfs, trip_id, keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector. Thetrip_ids used to filter the data.

keep

A logical. Whether the entries related to the specifiedtrip_ids should be kept or dropped (defaults toTRUE, which keeps theentries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_weekday()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_ids <- c("CPTM L07-0", "2002-10-0")object.size(gtfs)# keeps entries related to passed trip_idssmaller_gtfs <- filter_by_trip_id(gtfs, trip_ids)object.size(smaller_gtfs)# drops entries related to passed trip_idssmaller_gtfs <- filter_by_trip_id(gtfs, trip_ids, keep = FALSE)object.size(smaller_gtfs)

Filter GTFS object by weekday

Description

Filters a GTFS object by weekday, keeping (or dropping) the relevant entriesin each file.

Usage

filter_by_weekday(gtfs, weekday, combine = "or", keep = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

weekday

A character vector. The weekdays used to filter the data.Possible values arec("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday").

combine

A string. Specifies which logic operation (OR or AND) shouldbe used to filter the calendar table when multiple weekdays are specified.Defaults to"or". Please check the details and examples sections for moreinformation on this argument usage.

keep

A logical. Whether the entries related to the specified weekdaysshould be kept or dropped (defaults toTRUE, which keeps the entries).

Value

The GTFS object passed to thegtfs parameter, after the filteringprocess.

combine usage

When filtering the calendar table using weekdays, one could reason about theprocess in different ways. For example, you may want to keep only serviceswho run on mondays AND tuesdays. Or you may want to keep services that runEITHER on mondays OR on tuesdays. The first case is the equivalent offiltering using the expressionmonday == 1 & tuesday == 1, while the secondusesmonday == 1 | tuesday == 1. You can use thecombine argument tocontrol this behaviour.

Please note thatcombine also works together withkeep. Using the sameexamples listed above, you could either keep the entries related to servicesthat run on mondays and tuesdays or drop them, depending on the value youpass tokeep.

See Also

Other filtering functions:filter_by_agency_id(),filter_by_route_id(),filter_by_route_type(),filter_by_service_id(),filter_by_sf(),filter_by_shape_id(),filter_by_spatial_extent(),filter_by_stop_id(),filter_by_time_of_day(),filter_by_trip_id()

Examples

# read gtfsdata_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)object.size(gtfs)# keeps entries related to services than run EITHER on monday OR on sundaysmaller_gtfs <- filter_by_weekday(gtfs, weekday = c("monday", "sunday"))smaller_gtfs$calendar[, c("service_id", "monday", "sunday")]object.size(smaller_gtfs)# keeps entries related to services than run on monday AND on sundaysmaller_gtfs <- filter_by_weekday(  gtfs,  weekday = c("monday", "sunday"),  combine = "and")smaller_gtfs$calendar[, c("service_id", "monday", "sunday")]object.size(smaller_gtfs)# drops entries related to services than run EITHER on monday OR on sunday# the resulting gtfs shouldn't include any trips running on these dayssmaller_gtfs <- filter_by_weekday(  gtfs,  weekday = c("monday", "sunday"),  keep = FALSE)smaller_gtfs$calendar[, c("service_id", "monday", "sunday")]object.size(smaller_gtfs)# drops entries related to services than run on monday AND on sunday# the resulting gtfs may include trips that run on these days, but no trips# that run on both these dayssmaller_gtfs <- filter_by_weekday(  gtfs,  weekday = c("monday", "sunday"),  combine = "and",  keep = FALSE)smaller_gtfs$calendar[, c("service_id", "monday", "sunday")]object.size(smaller_gtfs)

Convert frequencies to stop times

Description

Createsstop_times entries based on the frequencies specified in thefrequencies table.

Usage

frequencies_to_stop_times(gtfs, trip_id = NULL, force = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector including thetrip_ids to have theirfrequencies converted tostop_times entries. IfNULL (the default), thefunction converts all trips listed in thefrequencies table.

force

Whether to convert trips specified in thefrequencies tableeven if they are not described instop_times (defaults toFALSE). Whenset toTRUE, these mismatched trip are removed from thefrequencies tableand their correspondent entries intrips are substituted by what would betheir converted counterpart.

Value

A GTFS object with updatedfrequencies,stop_times andtripstables.

Details

A single trip described in afrequencies table may yield multiple tripsafter converting the GTFS. Let's say, for example, that thefrequenciestable describes a trip called"example_trip", that starts at 08:00 andstops at 09:00, with a 30 minutes headway.

In practice, that means that one trip will depart at 08:00, another at 08:30and yet another at 09:00.frequencies_to_stop_times() appends a"_<n>"suffix to the newly created trips to differentiate each one of them (e.g. inthis case, the new trips, described in thetrips andstop_times tables,would be called"example_trip_1","example_trip_2" and"example_trip_3").

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip <- "CPTM L07-0"# converts all trips listed in the frequencies tableconverted_gtfs <- frequencies_to_stop_times(gtfs)# converts only the specified trip_idconverted_gtfs <- frequencies_to_stop_times(gtfs, trip)# how the specified trip_id was described in the frequencies tablehead(gtfs$frequencies[trip_id == trip])# the first row of each equivalent stop_times entry in the converted gtfsequivalent_stop_times <- converted_gtfs$stop_times[grepl(trip, trip_id)]equivalent_stop_times[equivalent_stop_times[, .I[1], by = trip_id]$V1]

Get children stops recursively

Description

Returns the (recursive) children stops of each specifiedstop_id.Recursive in this context means it returns all children's children (i.e.first children, then children's children, and then their children, and soon).

Usage

get_children_stops(gtfs, stop_id = NULL)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

stop_id

A string vector including thestop_ids to have theirchildren returned. IfNULL (the default), the function returns thechildren of everystop_id in the GTFS.

Value

Adata.table containing thestop_ids and their children'stop_ids. If a stop doesn't have a child, its correspondentchild_identry is marked as"".

Examples

data_path <- system.file("extdata/ggl_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)children <- get_children_stops(gtfs)head(children)# use the stop_id argument to control which stops are analyzedchildren <- get_children_stops(gtfs, stop_id = c("F12S", "F12N"))children

Get parent stations recursively

Description

Returns the (recursive) parent stations of each specifiedstop_id.Recursive in this context means it returns all parents' parents (i.e. firstparents, then parents' parents, and then their parents, and so on).

Usage

get_parent_station(gtfs, stop_id = NULL)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

stop_id

A string vector including thestop_ids to have their parentsreturned. IfNULL (the default), the function returns the parents ofeverystop_id in the GTFS.

Value

Adata.table containing thestop_ids and theirparent_stations.If a stop doesn't have a parent, its correspondentparent_station entryis marked as"".

See Also

get_children_stops()

Examples

data_path <- system.file("extdata/ggl_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)parents <- get_parent_station(gtfs)head(parents)# use the stop_id argument to control which stops are analyzedparents <- get_parent_station(gtfs, c("B1", "B2"))parents

Get stop times patterns

Description

Identifies spatial and spatiotemporal patterns within thestop_timestable. Please see the details to understand what a "pattern" means in each ofthese cases.

Usage

get_stop_times_patterns(  gtfs,  trip_id = NULL,  type = "spatial",  sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector including thetrip_ids to have theirstop_times entries analyzed. IfNULL (the default), the functionanalyses the pattern of everytrip_id in the GTFS.

type

A string specifying the type of patterns to be analyzed. Either"spatial" (the default) or "spatiotemporal".

sort_sequence

A logical specifying whether to sort timetables bystop_sequence. Defaults toFALSE, otherwise spec-compliant feeds, inwhich timetables points are already ordered bystop_sequence, would bepenalized through longer processing times. Pattern identification based onunordered timetables may result in multiple ids identifying what would bethe same pattern, had the table been ordered.

Value

Adata.table associating eachtrip_id to apattern_id.

Details

Two trips are assigned to the same spatialpattern_id if they travel alongthe same sequence of stops. They are assigned to the same spatiotemporalpattern_id, on the other hand, if they travel along the same sequence ofstops and they take the same time between stops. Please note that, in suchcase, only the time between stops is taken into account, and the time thatthe trip started is ignored (e.g. if two trips depart from stop A and followthe same sequence of stops to arrive at stop B, taking both 1 hour to do so,their spatiotemporal pattern will be considered the same, even if onedeparted at 6 am and another at 7 am). Please also note that thestop_sequence field is currently ignored - which means that two stops areconsidered to follow the same sequence if one is listed right below theother on thestop_times table (e.g. if trip X lists stops A followed bystop B withstop_sequences 1 and 2, and trip Y lists stops A followed bystop B withstop_sequences 1 and 3, they are assigned to the samepattern_id).

Examples

data_path <- system.file("extdata/ber_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)patterns <- get_stop_times_patterns(gtfs)head(patterns)# use the trip_id argument to control which trips are analyzedpatterns <- get_stop_times_patterns(  gtfs,  trip_id = c("143765658", "143765659", "143765660"))patterns# use the type argument to control the type of pattern analyzedpatterns <- get_stop_times_patterns(  gtfs,  trip_id = c("143765658", "143765659", "143765660"),  type = "spatiotemporal")patterns

Get trip duration

Description

Returns the duration of each specifiedtrip_id.

Usage

get_trip_duration(gtfs, trip_id = NULL, unit = "min")

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A string vector including thetrip_ids to have theirduration calculated. IfNULL (the default) the function calculates theduration of everytrip_id in the GTFS.

unit

A string representing the time unit in which the duration isdesired. One of"s" (seconds),"min" (minutes, the default),"h"(hours) or"d" (days).

Value

Adata.table containing the duration of each specified trip.

Details

The duration of a trip is defined as the time difference between its lastarrival time and its first departure time, as specified in thestop_timestable.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_duration <- get_trip_duration(gtfs)head(trip_duration)trip_ids <- c("CPTM L07-0", "2002-10-0")trip_duration <- get_trip_duration(gtfs, trip_id = trip_ids)trip_durationtrip_duration <- get_trip_duration(gtfs, trip_id = trip_ids, unit = "h")trip_duration

Get trip geometry

Description

Returns the geometry of each specifiedtrip_id, based either on theshapes or thestop_times file (or both).

Usage

get_trip_geometry(  gtfs,  trip_id = NULL,  file = NULL,  crs = 4326,  sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector including thetrip_ids to have theirgeometries generated. IfNULL (the default), the function generatesgeometries for everytrip_id in the GTFS.

file

A character vector specifying the file from which geometriesshould be generated (either one of or bothshapes andstop_times). IfNULL (the default), the function attemps to generate the geometries fromboth files, but only raises an error if none of the files exist.

crs

The CRS of the resulting object, either as an EPSG code or as ancrs object. Defaults to 4326 (WGS 84).

sort_sequence

A logical specifying whether to sort shapes andtimetables byshape_pt_sequence andstop_sequence, respectively.Defaults toFALSE, otherwise spec-compliant feeds, in whichshape/timetables points are already ordered byshape_pt_sequence/stop_sequence, would be penalized through longerprocessing times. Geometries generated from unordered sequences do notcorrectly depict the trip trajectories.

Value

A⁠LINESTRING sf⁠.

Details

The geometry generation works differently for the two files. In the case ofshapes, the shape as described in the text file is converted to ansfobject. Forstop_times the geometry is the result of linking subsequentstops along a straight line (stops' coordinates are retrieved from thestops file). Thus, the resolution of the geometry when generated withshapes tends to be much higher than when created withstop_times.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_geometry <- get_trip_geometry(gtfs)head(trip_geometry)# the above is identical totrip_geometry <- get_trip_geometry(gtfs, file = c("shapes", "stop_times"))head(trip_geometry)trip_ids <- c("CPTM L07-0", "2002-10-0")trip_geometry <- get_trip_geometry(gtfs, trip_id = trip_ids)trip_geometryplot(trip_geometry["origin_file"])

Get trip length

Description

Returns the length of each specifiedtrip_id, based either on theshapesor thestop_times file (or both).

Usage

get_trip_length(  gtfs,  trip_id = NULL,  file = NULL,  unit = "km",  sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector including thetrip_ids to have theirlength calculated IfNULL (the default), the function calculates thelength of eachtrip_id in the GTFS.

file

A character vector specifying the file from which lengths shouldbe calculated (either one of or bothshapes andstop_times). IfNULL(the default), the function attempts to calculate the lengths from bothfiles, but only raises an error if none of the files exist.

unit

A string representing the unit in which lengths are desired.Either"km" (the default) or"m".

sort_sequence

A logical specifying whether to sort shapes andtimetables byshape_pt_sequence andstop_sequence, respectively.Defaults toFALSE, otherwise spec-compliant feeds, in whichshape/timetables points are already ordered byshape_pt_sequence/stop_sequence, would be penalized through longerprocessing times. Lengths calculated from trip trajectories generated withunordered sequences do not correctly depict the actual trip lengths.

Value

Adata.table containing the length of each specified trip.

Details

Please checkget_trip_geometry() documentation to understand how geometrygeneration, and consequently length calculation, differs depending on thechosen file.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_length <- get_trip_length(gtfs)head(trip_length)# the above is identical totrip_length <- get_trip_length(gtfs, file = c("shapes", "stop_times"))head(trip_length)trip_ids <- c("CPTM L07-0", "2002-10-0")trip_length <- get_trip_length(gtfs, trip_id = trip_ids)trip_length

Get trip segments' duration

Description

Returns the duration of segments between stops of each specifiedtrip_id.

Usage

get_trip_segment_duration(  gtfs,  trip_id = NULL,  unit = "min",  sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A string vector including thetrip_ids to have theirsegments' duration calculated. IfNULL (the default) the functioncalculates the segments' duration of everytrip_id in the GTFS.

unit

A string representing the time unit in which the duration isdesired. One of"s" (seconds),"min" (minutes, the default),"h" (hours) or"d" (days).

sort_sequence

A logical specifying whether to sort timetables bystop_sequence. Defaults toFALSE, otherwise spec-compliant feeds, inwhich timetables points are already ordered bystop_sequence, would bepenalized through longer processing times. Durations calculated fromunordered timetables do not correctly depict the real life segmentdurations.

Value

Adata.table containing the segments' duration of each specifiedtrip.

Details

A trip segment is defined as the path between two subsequent stops in thesame trip. The duration of a segment is defined as the time differencebetween its arrival time and its departure time, as specified in thestop_times file.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_segment_dur <- get_trip_segment_duration(gtfs)head(trip_segment_dur)# use the trip_id argument to control which trips are analyzedtrip_segment_dur <- get_trip_segment_duration(gtfs, trip_id = "CPTM L07-0")trip_segment_dur# use the unit argument to control in which unit the durations are calculatedtrip_segment_dur <- get_trip_segment_duration(gtfs, "CPTM L07-0", unit = "s")trip_segment_dur

Get trip speed

Description

Returns the speed of each specifiedtrip_id, based on the geometry createdfrom either theshapes or thestop_times file (or both).

Usage

get_trip_speed(  gtfs,  trip_id = NULL,  file = "shapes",  unit = "km/h",  sort_sequence = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A character vector including thetrip_ids to have theirspeeds calculated. IfNULL (the default), the function calculates thespeed of everytrip_id in the GTFS.

file

The file from which geometries should be generated, eithershapes orstop_times (geometries are used to calculate the length of atrip). Defaults toshapes.

unit

A string representing the unit in which the speeds are desired.Either"km/h" (the default) or"m/s".

sort_sequence

Ultimately passed toget_trip_length(), a logicalspecifying whether to sort shapes and timetables byshape_pt_sequence andstop_sequence, respectively. Speeds calculated from trip trajectoriesgenerated with unordered sequences do not correctly depict the actual tripspeeds. Defaults toFALSE, otherwise spec-compliant feeds, in whichshape/timetables points are already ordered byshape_pt_sequence/stop_sequence, would be penalized through longerprocessing times.

Value

Adata.table containing the duration of each specified trip and thefile from which geometries were generated.

Details

Please checkget_trip_geometry() documentation to understand how geometrygeneration differs depending on the chosen file.

See Also

get_trip_geometry()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)trip_speed <- get_trip_speed(gtfs)head(trip_speed)trip_ids <- c("CPTM L07-0", "2002-10-0")trip_speed <- get_trip_speed(gtfs, trip_ids)trip_speedtrip_speed <- get_trip_speed(  gtfs,  trip_ids,  file = c("shapes", "stop_times"))trip_speedtrip_speed <- get_trip_speed(gtfs, trip_ids, unit = "m/s")trip_speed

Convert an integer vector into a Date vector

Description

Convert an integer vector into a Date vector

Usage

integer_to_date(field)

Merge GTFS files

Description

Combines many GTFS objects into a single one.

Usage

merge_gtfs(..., files = NULL, prefix = FALSE)

Arguments

...

GTFS objects to be merged. Each argument can either be a GTFS ora list of GTFS objects.

files

A character vector listing the GTFS tables to be merged. IfNULL (the default), all tables are merged.

prefix

Either a logical or a character vector (defaults toFALSE).Whether to add a prefix to the value of id fields that identify from whichGTFS object the value comes from. IfTRUE, the prefixes will range from"1" ton, wheren is the number of objects passed to the function. If acharacter vector, its elements will be used to identify the GTFS objects, andthe length of the vector must equal the total amount of objects passed in... (the first element will identify the first GTFS, the second element thesecond GTFS, and so on).

Value

A GTFS object in which each table is a combination (by row) of thetables from the specified GTFS objects.

Examples

spo_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")ggl_path <- system.file("extdata/ggl_gtfs.zip", package = "gtfstools")spo_gtfs <- read_gtfs(spo_path)names(spo_gtfs)ggl_gtfs <- read_gtfs(ggl_path)names(ggl_gtfs)merged_gtfs <- merge_gtfs(spo_gtfs, ggl_gtfs)names(merged_gtfs)# use a list() to programatically merge many GTFS objectsgtfs_list <- list(spo_gtfs, ggl_gtfs)merged_gtfs <- merge_gtfs(gtfs_list)# 'prefix' helps disambiguating from which GTFS each id comes from.# if TRUE, the ids range from 1:n, where n is the number of gtfsmerged_gtfs <- merge_gtfs(gtfs_list, prefix = TRUE)merged_gtfs$agency# if a character vector, its elements will be used to identify the each gtfsmerged_gtfs <- merge_gtfs(gtfs_list, prefix = c("spo", "ggl"))merged_gtfs$agency

Read GTFS files

Description

Reads GTFS text files from either a local.zip file or an URL.

Usage

read_gtfs(  path,  files = NULL,  fields = NULL,  skip = NULL,  quiet = TRUE,  encoding = "unknown")

Arguments

path

The path to a GTFS.zip file.

files

A character vector containing the text files to be read from theGTFS (without the.txt extension). IfNULL (the default) all existingfiles are read.

fields

A named list containing the fields to be read from each textfile, in the formatlist(file = c("field1", "field2")). IfNULL (thedefault), all fields from the files specified infiles are read. If afile is specified infiles but not infields, all fields from that filewill be read (i.e. you may specify infields only files whose fields youwant to subset).

skip

A character vector containing the text files that should not beread from the GTFS, without the.txt extension. IfNULL (the default),no files are skipped. Cannot be used iffiles is already set.

quiet

Whether to hide log messages and progress bars (defaults toTRUE).

encoding

A string, ultimately passed todata.table::fread().Defaults to"unknown". Other possible options are"UTF-8" and"Latin-1". Please note that this is not used to re-encode the input, butto enable handling encoded strings in their native encoding.

Value

Adata.table-based GTFS object: alist ofdata.tables in whicheach table represents a GTFS text file.

Details

The column types of eachdata.table in the final GTFS object conform asclosely as possible to theGoogle's Static GTFS Reference. Exceptions aredate-related columns (such ascalendar.txt'sstart_date andend_date,for example), which are converted toDate objects, instead of being kept asintegers, allowing for easier data manipulation. These columns areconverted back tointegers when writing the GTFS object to a.zip fileusingwrite_gtfs().

See Also

Other io functions:write_gtfs()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)names(gtfs)gtfs <- read_gtfs(data_path, files = c("trips", "stop_times"))names(gtfs)gtfs <- read_gtfs(data_path, skip = "trips")names(gtfs)gtfs <- read_gtfs(data_path, fields = list(agency = "agency_id"))names(gtfs)names(gtfs$agency)

Remove duplicated entries

Description

Removes duplicated entries from GTFS objects tables.

Usage

remove_duplicates(gtfs)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

Value

A GTFS object containing only unique entries.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)# this gtfs includes some duplicated entriesgtfs$agencygtfs <- remove_duplicates(gtfs)gtfs$agency

Convert seconds after midnight to time string

Description

Converts seconds after midnight as integers to strings in the "HH:MM:SS"format.

Usage

seconds_to_string(seconds)

Arguments

seconds

An integer.

Value

A time-representing string.


Set trip average speed

Description

Sets the average speed of each specifiedtrip_id by changing thearrival_time anddeparture_time columns instop_times.

Usage

set_trip_speed(gtfs, trip_id, speed, unit = "km/h", by_reference = FALSE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

trip_id

A string vector including thetrip_ids to have theiraverage speed set.

speed

A numeric representing the speed to be set. Its length musteither equal 1, in which case the value is recycled for alltrip_ids, or equaltrip_id's length.

unit

A string representing the unit in which the speed is given. Oneof"km/h" (the default) or"m/s".

by_reference

Whether to updatestop_times'data.table byreference. Defaults toFALSE.

Value

Ifby_reference is set toFALSE, returns a GTFS object with thetime columns of itsstop_times adjusted. Else, returns a GTFS objectinvisibly (note that in this case the original GTFS object is altered).

Details

The average speed is calculated as the difference between the arrival timeat the last stop minus the departure time at the first top, over the trip'slength (as calculated viaget_trip_geometry(), based on theshapesfile). The arrival and departure times at all other stops (i.e. not thefirst neither the last) are set as"", which is written asNA withwrite_gtfs(). Some transport routing software, such asOpenTripPlanner, support specifying stoptimes like so. In such cases, they estimate arrival/departure times at theothers stops based on the average speed as well. We plan to add that featureto this function in the future.

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)gtfs_new_speed <- set_trip_speed(gtfs, trip_id = "CPTM L07-0", 50)gtfs_new_speed$stop_times[trip_id == "CPTM L07-0"]# use the unit argument to change the speed unitgtfs_new_speed <- set_trip_speed(  gtfs,  trip_id = "CPTM L07-0",  speed = 15,  unit = "m/s")gtfs_new_speed$stop_times[trip_id == "CPTM L07-0"]# original gtfs remains unchangedgtfs$stop_times[trip_id == "CPTM L07-0"]# when doing by reference, original gtfs is changedset_trip_speed(gtfs, trip_id = "CPTM L07-0", 50, by_reference = TRUE)gtfs$stop_times[trip_id == "CPTM L07-0"]

Convert time string to seconds after midnight

Description

Converts strings in the "HH:MM:SS" format to seconds after midnight.

Usage

string_to_seconds(string)

Arguments

string

A string in "HH:MM:SS" format.

Value

The seconds after midnight of a given time string as an integer.


Validate GTFS feed

Description

Uses MobilityData'sGTFS validator to perform a GTFSbusiness rule validation. The results are available as an HTML report (ifvalidator v3.1.0 or higher is used) and in JSON format. Please check thecomplete set of rules used in the validationhere.Please note that this function requires a working installation of Java 11 orhigher to work.

Usage

validate_gtfs(  gtfs,  output_path,  validator_path,  overwrite = TRUE,  html_preview = TRUE,  pretty_json = FALSE,  quiet = TRUE,  n_threads = 1)

Arguments

gtfs

The GTFS to be validated. Can be in the format of a GTFS object,of a path to a GTFS file, of a path to a directory or an URL to a feed.

output_path

A string. The path to the directory that the validatorwill create and in which the results will be saved to.

validator_path

A string. The path to the GTFS validator, previouslydownloaded withdownload_validator().

overwrite

A logical. Whether to overwrite existing validation resultsinoutput_path. Defaults toTRUE.

html_preview

A logical. Whether to show HTML report in a viewer, suchas RStudio or a browser. Defaults toTRUE (only works on interactivesessions).

pretty_json

A logical. Whether JSON results should be printed in areadable way, that allows it to be inspected without manually formatting.Defaults toFALSE.

quiet

A logical. Whether to hide informative messages. Defaults toTRUE.

n_threads

An integer between 1 and the number of cores in the runningmachine. Control how many threads are used during the validation. Defaultsto using all but one of the available cores.

Value

Invisibly returns the normalized path to the directory where thevalidation results were saved to.

See Also

Other validation:download_validator()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")output_path <- tempfile("validation_result")validator_path <- download_validator(tempdir())gtfs <- read_gtfs(data_path)validate_gtfs(gtfs, output_path, validator_path)list.files(output_path)# works with feeds saved to disknew_output_path <- tempfile("new_validation_result")validate_gtfs(data_path, new_output_path, validator_path)list.files(new_output_path)# and with feeds pointed by an urlnewer_output_path <- tempfile("newer_validation_result")gtfs_url <- "https://github.com/ipeaGIT/gtfstools/raw/main/inst/extdata/spo_gtfs.zip"validate_gtfs(gtfs_url, newer_output_path, validator_path)list.files(newer_output_path)

Write GTFS files

Description

Writes GTFS objects as GTFS.zip files.

Usage

write_gtfs(  gtfs,  path,  files = NULL,  standard_only = FALSE,  as_dir = FALSE,  overwrite = TRUE,  quiet = TRUE)

Arguments

gtfs

A GTFS object, as created byread_gtfs().

path

The path to the.zip file in which the feed should be writtento.

files

A character vector containing the name of the elements to bewritten to the feed. IfNULL (the default), all elements inside the GTFSobject are written.

standard_only

Whether to write only standard files and fields(defaults toFALSE, which doesn't drop extra files and fields).

as_dir

Whether to write the feed as a directory, instead of a.zipfile (defaults toFALSE, which means that the field is written as a zipfile).

overwrite

Whether to overwrite existing.zip file (defaults toTRUE).

quiet

Whether to hide log messages and progress bars (defaults toTRUE).

Value

Invisibly returns the same GTFS object passed to thegtfsparameter.

See Also

Other io functions:read_gtfs()

Examples

data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")gtfs <- read_gtfs(data_path)tmp_dir <- file.path(tempdir(), "tmpdir")dir.create(tmp_dir)list.files(tmp_dir) #'tmp_file <- tempfile(pattern = "gtfs", tmpdir = tmp_dir, fileext = ".zip")write_gtfs(gtfs, tmp_file)list.files(tmp_dir)gtfs_all_files <- read_gtfs(tmp_file)names(gtfs_all_files)write_gtfs(gtfs, tmp_file, files = "stop_times")gtfs_stop_times <- read_gtfs(tmp_file)names(gtfs_stop_times)

[8]ページ先頭

©2009-2025 Movatter.jp