Package 'swissgeo.core'

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-1
Built: 2026-10-07 11:52:13 UTC
Source: http://codeberg.org/retostauffer/swissgeo.core

Help Index


Assets

Description

Each item as returned by sg_items() 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.

Usage

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, ...)

Arguments

x

object of class 'assets'.

...

currently ignored.

i

elements to extract or replace. Numeric values coerced to integer identifying the ith element(s) for subsetting.

row.names

NULL (default) or a character vector giving the row names for the data frame. Only used if x is of length 1L.

optional

currently ignored.

Value

An asset data frame with the name of the asset and all provided additional information.

Author(s)

Reto


Converting Datetime Columns

Description

Takes a data frame as input and tries to identify columns containing datetime information.

Usage

autoconvert_datetime(x)

Arguments

x

data frame.

Details

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

Value

Data frame with POSIXct variables if any variable containing datetime information was detected.

Author(s)

Reto

Examples

## 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)

Convert Dataframe to Simple Feature Dataframe

Description

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.

Usage

dataframe_to_sf(x, use_crs = c("lv95", "wgs84"), verbose = FALSE)

Arguments

x

a data frame which (potentially) contains coordinates.

use_crs

character, order of coordinate reference to use (if found).

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

Details

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.

Value

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

Description

Removing Non-required Language-specific Variables

Usage

remove_language_cols(x, lang)

Arguments

x

data frame to be checked and potentially modified.

lang

character, languages to keep. If "all" no modifications are done. Else trying to remove all columns not matching the requested lang.

Value

A data frame, potentially modified by removing all columns not matching the requested language.

Author(s)

Reto


Collection Assets

Description

Retrieving all assets of a specific collection.

Usage

sg_assets(id, raw = FALSE, verbose = FALSE)

Arguments

id

character, ID of the collection for which to retrieve the items (see sg_collections()).

raw

logical, defaults to FALSE (see Return).

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

Value

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).

Author(s)

Reto


Modify Request URL

Description

Modifies the URL of an existing httr2_request object.

Usage

sg_change_url(req, ...)

Arguments

req

object of class httr2_request.

...

additional arguments to extend the base API URL. All arguments (after coercion to character) must represent valid non-empty characters.

Value

Returns a modified version of the input argument req with an updated (API) URL.

Author(s)

Reto


Collections

Description

Requesting a list of all available collections provided via the API.

Usage

sg_collections(pattern = NULL, verbose = FALSE, raw = FALSE)

Arguments

pattern

NULL or a pattern used return a subset of all available collections, applied to the collection ID.

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

raw

logical, defaults to FALSE (see Return).

Value

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.

Author(s)

Reto

Examples

## 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

Description

Download (Cache) and Import Assets/Data Sets

Usage

sg_download_assets(
  x,
  dir = NULL,
  language = c("all", "en", "de", "fr", "it"),
  use_crs = c("lv95", "wgs84"),
  encoding = "Latin1",
  read_csv = TRUE,
  cachedir = NULL,
  verbose = FALSE
)

Arguments

x

data frame (with one row) or list containing at least the following variables: id, type, href, file:checksum.

dir

NULL or character, name/path to a directory where to store the file. Note that no file will be stored if CVS files are downloaded and read_csv = TRUE.

language

character, one of "all" (default), "en", "de", "fr", or "it". If set different to "all" columns ending in ⁠_<lang>⁠ not matching the requested language will be removed.

use_crs

character vector used to auto-detect coordinates. Can be set to NULL/FALSE to not do the conversion.

encoding

file encoding, only used if the asset is a CSV file and read_csv is set TRUE.

read_csv

logical, defaults to TRUE. If TRUE and the asset is a csv file it will be read and returned.

cachedir

NULL or character, path to a cache directory. If set, the downloaded files are cached and re-used if needed.

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

Details

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 cache directory is specified (cachedir) 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 again. 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.

Author(s)

Reto


Collection Items

Description

Retrieving all items of a specific collection.

Usage

sg_items(id, raw = FALSE, verbose = FALSE)

Arguments

id

character, ID of the collection for which to retrieve the items (see sg_collections()).

raw

logical, defaults to FALSE (see Return).

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

Value

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).

Author(s)

Reto

Examples

## 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)

Setting swissgeo Options

Description

Allows the user to overwrite a series of default options used in the package, mainly fine-tuning how the HTTPS requests are handled.

Usage

sg_options(
  timeout = 20,
  retry = 3,
  capacity = 3,
  filltime = 3,
  apiurl = NULL,
  verbose = FALSE
)

Arguments

timeout

positive numeric, forwarded to httr2::req_timeout(). Defaults to 20 seconds.

retry

positive integer, forwarded to httr2::req_retry(). Defaults to 3 (three retries).

capacity

positive integer, forwarded to httr2::req_throttle(). Defaults to size 3.

filltime

positive numeric, forwarded to httr2::req_throttle(). Defaults to size 3.

apiurl

NULL (default) or character. Allows to overwrite the main URL (mainly for testing).

verbose

logical, defaults to FALSE.

Details

A series of default options is set every time the package is attached. They can be overruled by the user calling this function.

Value

Invisibly returns the current swissgeo settings, these are used in the ⁠sg_*⁠ functions for request handling.

Author(s)

Reto


Get Request Helper Function

Description

Auxilary function to send HTTPS requests with additional error handling. Requests are sent over the httr2 requests object (see sg_options() for details).

Usage

sg_send_api_request(
  req,
  query = NULL,
  paging = FALSE,
  limit = 100L,
  verbose = FALSE,
  ...
)

Arguments

req

object of class httr2_request.

query

NULL (default) or a list with get parameters to be sent with the request. Warning: If the URL contains get requests and query is not NULL, the parameters in the URL (url) will be overwritten!

paging

logical, defaults to FALSE. If TRUE we will send an initial request is sent to the url which returns a maximum of 100 entries. It is then checked if a 'next' link is included in the response used to request the next batch of up to 100 entries until finished.

limit

integer, defaults to 100L. Number of entries to be requested if paging = TRUE.

verbose

logical, defaults to FALSE. If set TRUE the some messages are printed.

...

forwarded to the httr::GET() function. TODO(R)

Details

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.

Value

List with the decoded information.

Author(s)

Reto