| Title: | Core Package to Access Data via the Geoportal des Bundes (Swiss Federal Government Open Data Portal) |
|---|---|
| Description: | Package to download data from data.geo.admin.ch. |
| Authors: | Reto Stauffer [aut, cre] (ORCID: <https://orcid.org/0000-0002-3798-5507>) |
| Maintainer: | Reto Stauffer <[email protected]> |
| License: | GPL-2 |
| Version: | 0.0-9001 |
| Built: | 2026-07-01 19:28:42 UTC |
| Source: | http://codeberg.org/retostauffer/swissgeo.core |
Each item can provide multiple assets. An asset specifies the type of data
(e.g., historical, recent) as well as the temporal resolution of the data
and the data period (if suitable). The sg_assets class is used to handle
these assets within the package.
assets(x) ## S3 method for class 'assets' format(x, ...) ## S3 method for class 'assets' print(x, ...) ## S3 method for class 'assets' x[i, ...] ## S3 method for class 'assets' as.double(x, ...) ## S3 method for class 'assets' names(x) ## S3 method for class 'assets' as.data.frame(x, row.names = NULL, optional = NA, ...)assets(x) ## S3 method for class 'assets' format(x, ...) ## S3 method for class 'assets' print(x, ...) ## S3 method for class 'assets' x[i, ...] ## S3 method for class 'assets' as.double(x, ...) ## S3 method for class 'assets' names(x) ## S3 method for class 'assets' as.data.frame(x, row.names = NULL, optional = NA, ...)
x |
object of class 'assets'. |
... |
currently ignored. |
i |
elements to extract or replace. Numeric values coerced
to integer identifying the |
row.names |
|
optional |
currently ignored. |
An asset data frame with the name of the asset and all provided additional information.
Reto
Takes a data frame as input and tries to identify columns containing datetime information.
autoconvert_datetime(x)autoconvert_datetime(x)
x |
data frame. |
Data received by the API or read via the files provided regularey contain date or datetime information as character strings.
This function takes a data frame and tries to identify variables/columns containing date and time information to coerce the information into Date or POSIXct objects. Currently, the following formats are checked currently:
2026-01-16T17:34:34(...)Z: converted to POSIXct
16.01.2026: converted to Date
2026-01-16: converted to Date
16.01.2026 12:03: converted to POSIXct w/ time zone Europe/Zuerich
16.01.2026 00:00: converted to Date
Data frame with POSIXct variables if any variable containing datetime information was detected.
Reto
## Not run: autoconvert_datetime(data.frame(a = 1, b = "2026-01-16T12:34:56.23435Z")) autoconvert_datetime(data.frame(a = 1, b = "2026-01-16T12:34:56Z")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026 12:34")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026 00:00")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026")) autoconvert_datetime(data.frame(a = 1, b = "2026-01-16")) ## End(Not run)## Not run: autoconvert_datetime(data.frame(a = 1, b = "2026-01-16T12:34:56.23435Z")) autoconvert_datetime(data.frame(a = 1, b = "2026-01-16T12:34:56Z")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026 12:34")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026 00:00")) autoconvert_datetime(data.frame(a = 1, b = "16.01.2026")) autoconvert_datetime(data.frame(a = 1, b = "2026-01-16")) ## End(Not run)
Many data sets retrieved via the Geoportal are geolocated, providing coordinates of e.g., a station location. This function tries to auto-detect locations, converting a dataframe into a simple feature dataframe.
dataframe_to_sf(x, use_crs = c("lv95", "wgs84"), verbose = FALSE)dataframe_to_sf(x, use_crs = c("lv95", "wgs84"), verbose = FALSE)
x |
a data frame which (potentially) contains coordinates. |
use_crs |
character, order of coordinate reference to use (if found). |
verbose |
logical, defaults to |
Some data sets like station locations come their geolocation (coordinates), sometimes given in two different reference systems. This function takes a data frame and checks if it can find coordinates. If found, the object is converted into a simple feature data frame dropping all coordinates from the data part.
If no matching coordinates are found, x is returned as is. Else
x is converted into a simple feature data frame, removing all coordinate
related columns.
Removing Non-required Language-specific Variables
remove_language_cols(x, lang)remove_language_cols(x, lang)
x |
data frame to be checked and potentially modified. |
lang |
character, languages to keep. If |
A data frame, potentially modified by removing all columns not matching the requested language.
Reto
Generate Geoportal API URLs
sg_api_url(req, ...)sg_api_url(req, ...)
... |
additional arguments to extend the base API URL. All arguments (after coercion to character) must represent valid non-empty characters. |
On loading the package sets the option "swissgeo.apiurl"
with the main entry point to the API. This is used inside this
function (i.e., by the entire package) to talk to the API.
This would allow users to change the end-point (or version) without updating the package, e.g., for testing.
Character of length one with the URL of the API end point.
Reto
## Base URL req <- getOption("swissgeo.req") sg_api_url(req)$url ## Extending the base URL to point to a specific API endpoint req |> sg_api_url("ch.meteoschweiz.ogd-smn")$url req |> sg_api_url("ch.meteoschweiz.ogd-smn", "items")$url ## Changing default API URL. Possible, but not a standard use-case. hold_apiurl <- getOption("swissgeo.apiurl") # kept for resetting options(swissgeo.apiurl = "https://some.new.domain/api/stac/v5") getOption("swissgeo.req") |> sg_api_url()$url ## Setting back to defaults options(swissgeo.apiurl = hold_apiurl) getOption("swissgeo.req") |> sg_api_url()$url## Base URL req <- getOption("swissgeo.req") sg_api_url(req)$url ## Extending the base URL to point to a specific API endpoint req |> sg_api_url("ch.meteoschweiz.ogd-smn")$url req |> sg_api_url("ch.meteoschweiz.ogd-smn", "items")$url ## Changing default API URL. Possible, but not a standard use-case. hold_apiurl <- getOption("swissgeo.apiurl") # kept for resetting options(swissgeo.apiurl = "https://some.new.domain/api/stac/v5") getOption("swissgeo.req") |> sg_api_url()$url ## Setting back to defaults options(swissgeo.apiurl = hold_apiurl) getOption("swissgeo.req") |> sg_api_url()$url
Retrieving all assets of a specific collection.
sg_assets(id, verbose = FALSE, raw = FALSE)sg_assets(id, verbose = FALSE, raw = FALSE)
id |
character, ID of the collection for which to retrieve
the items (see |
verbose |
logical, defaults to |
raw |
logical, defaults to |
A tbl data frame containing the asset details is returned.
If raw = TRUE a list of lists is returned with the raw (json decoded)
result from the API calls. Each element in the list corresponds to one API
call (paging).
Reto
Requesting a list of all available collections provided via the API.
sg_collections(pattern = NULL, verbose = FALSE, raw = FALSE)sg_collections(pattern = NULL, verbose = FALSE, raw = FALSE)
pattern |
|
verbose |
logical, defaults to |
raw |
logical, defaults to |
Returns a tibble data frame with the available collections.
If pattern = NULL all collections found are returned. If
a pattern is specified, all collections where the collection ID
(id) matches the pattern are returned. If no IDs match the
pattern, a warning is thrown and NULL is returned.
If raw = TRUE is specified, pattern is ignored and the raw
data as retrieved by the API are returned as a list of lists.
Each element of the list corresponds to one API call containing
a set of lists corresponding to the different collections returned.
Reto
## Not run: ## Fetch all available collections collections <- sg_collections() ## Extract collections by MeteoSchweiz subset(res, grepl("meteoschweiz", id)) ## End(Not run)## Not run: ## Fetch all available collections collections <- sg_collections() ## Extract collections by MeteoSchweiz subset(res, grepl("meteoschweiz", id)) ## End(Not run)
Download (Cache) and Import Assets/Data Sets
sg_download_asset( x, dir = NULL, language = c("all", "en", "de", "fr", "it"), use_crs = c("lv95", "wgs84"), verbose = FALSE )sg_download_asset( x, dir = NULL, language = c("all", "en", "de", "fr", "it"), use_crs = c("lv95", "wgs84"), verbose = FALSE )
x |
data frame (with one row) or list containing at least the following variables: id, type, href, file_checksum. |
dir |
character, name/path to a directory to cache the data sets (see 'Details' for more information). |
language |
character, one of |
use_crs |
character vector used to auto-detect coordinates.
Can be set to |
verbose |
logical, defaults to |
Assets (data sets) provided via geo.admin.ch come with a file checksum which can be used to check if a file changed. We use this to cache files.
If a directory is specified (dir) it will be checked if that file has
already been downloaded and stored in the directory. In this situation, the
local file is used rather than downloading the data. If not, the asset will
be downloaded and stored in the directory specified so that it can be
potentially used again next time.
Please note that the the size of the directory can grow fast, especially if this mechanic is used when downloading/accessing data sets that rapidly change (i.e., most recent data) as a new file will be created every time the checksum changes.
Reto
Retrieving all items of a specific collection.
sg_items(id, raw = FALSE, verbose = FALSE)sg_items(id, raw = FALSE, verbose = FALSE)
id |
character, ID of the collection for which to retrieve
the items (see |
raw |
logical, defaults to |
verbose |
logical, defaults to |
If raw = TRUE a list of lists is returned with the
raw (json decoded) result from the API calls. Each element in
the list corresponds to one API call (paging).
Else (default) the function tries to auto-detect the format. As an example, if the returned data are of type "FeatureCollection"s The data is converted to a simple feature data frame which is then returned. If now only "FeatureCollection" is implemented, if the returned data is of a different type the raw list is returned (TODO).
Reto
## Not run: ## Retrieving items for a collection w/ features CID <- "ch.meteoschweiz.ogd-smn" items <- sg_items(CID) ## Visualizing the features library("ggplot2") ggplot(st_transform(items, crs = st_crs(2056))) + geom_sf(col = "lightgreen") + geom_sf_text(aes(label = id)) ## End(Not run)## Not run: ## Retrieving items for a collection w/ features CID <- "ch.meteoschweiz.ogd-smn" items <- sg_items(CID) ## Visualizing the features library("ggplot2") ggplot(st_transform(items, crs = st_crs(2056))) + geom_sf(col = "lightgreen") + geom_sf_text(aes(label = id)) ## End(Not run)
swissgeo OptionsAllows the user to overwrite a series of default options used in the package, mainly fine-tuning how the HTTPS requests are handled.
sg_options( timeout = 20, retry = 3, capacity = 3, filltime = 3, apiurl = NULL, verbose = FALSE )sg_options( timeout = 20, retry = 3, capacity = 3, filltime = 3, apiurl = NULL, verbose = FALSE )
Defaults to 20 seconds.
A series of default options is set every time the package is attached. They can be overruled by the user calling this function.
Invisibly returns the current swissgeo settings, these are used
in the sg_* functions for request handling.
Reto
Auxilary function to send HTTPS requests with additional error handling.
Requests are sent over the httr2 requests object (see sg_options() for details).
sg_send_api_request( req, query = NULL, paging = FALSE, limit = 100L, verbose = FALSE, ... )sg_send_api_request( req, query = NULL, paging = FALSE, limit = 100L, verbose = FALSE, ... )
query |
|
paging |
logical, defaults to |
limit |
integer, defaults to |
verbose |
logical, defaults to |
... |
forwarded to the |
We are expecting a JSON response from the API, thus
we expect that the request content is decoded to a list by the
httr package. IF paging = FALSE this list is returned.
If paging = TRUE a list of lists is returned, where each
element in the main list contains the results of one API call
following the 'next' links (see argument paging).
If we do not get a proper HTTP status code, or the extracted content is not a list, this function will throw an error.
List with the decoded information.
Reto