SpatAn 1: Exercise B

Published

April 30, 2024

Task 1: Geopackage “Layers”

For the upcoming exercise, we will work with the gruental.gpkg. data set: Import it into R.

You may have noticed the following warning message when importing the gruental.gpkg geopackage:

Warning message:
In evalq((function (..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE,  :
  automatically selected the first layer in a data source containing more than one.

This warning message indicates that the geopackage gruental.gpkg has several layers (rep. records) and only the first layer has been imported. Use the st_layers command to find out the layer names and then use them in st_read (as argument layer =) to import the layers individually and store them in variables (e.g., such as in the variables wiesen and baeume).

Sample Solution
st_layers("datasets/rauman/gruental.gpkg")
## Driver: GPKG 
## Available layers:
##   layer_name geometry_type features fields       crs_name
## 1     wiesen       Polygon       37      1 CH1903+ / LV95
## 2     baeume         Point      185      2 CH1903+ / LV95

meadows <- read_sf("datasets/rauman/gruental.gpkg", "wiesen")
trees <- read_sf("datasets/rauman/gruental.gpkg", "baeume")

Task 2: Understanding the data sets

Take some time to explore the two datasets. Use the visualisation options of ggplot (especially geom_sf). You can superimpose multiple geom_sf to represent multiple records at the same time.

Sample Solution
library("ggplot2")

ggplot(meadows) +
  geom_sf(aes(fill = flaechen_typ)) +
  geom_sf(data = trees) +
  theme_void()

ggplot(meadows) +
  geom_sf() +
  geom_sf(data = trees, aes(colour = baum_typ)) +
  theme_void()
Figure 20.1: Meadow areas are shown in different colours depending on type
Figure 20.2: Trees are shown in different colours depending on type

Task 3: Spatial join with points

We now want to know whether each tree is in a meadow or not. To do this, we use the GIS technique spatial join as described in the lecture. Using sf, we can perform spatial joins with st_join. There are only left and innerjoins (see PrePro 1 & 2). The points must be listed first, since we want to attach attributes to the points.

Note that the output has a new column: flaechen_typ. This is empty (NA) if the corresponding tree is not in a meadow. How many trees are in a meadow and how many are not?

Sample Solution
trees_join <- st_join(trees, meadows)

number_in_meadow <- sum(!is.na(trees_join$flaechen_typ))
number_not_in_meadow <- sum(is.na(trees_join$flaechen_typ))