Solutions

Tip

Hover over the code and copy the content by clicking on the clipboard icon on the top right. You can now paste this into an R-Script.

Exercise A

# task_1.R
################################################################################


library("readr")
library("sf")

wildschwein_BE <- read_delim("datasets/wildschwein_BE_2056.csv", ",")

wildschwein_BE <- st_as_sf(wildschwein_BE, coords = c("E", "N"), crs = 2056)




# task_2.R
################################################################################


library("dplyr")      # move this to the top of your script
library("lubridate")  # move this to the top of your script
library("ggplot2")    # move this to the top of your script

ggplot(wildschwein_BE, aes(DatetimeUTC, TierID)) +
  geom_line()


difftime_secs <- function(x, y){
  as.numeric(difftime(x, y, units = "secs"))
}


wildschwein_BE <- wildschwein_BE |>
  mutate(timelag = difftime_secs(lead(DatetimeUTC), DatetimeUTC))



ggplot(wildschwein_BE, aes(timelag)) +
  geom_histogram(binwidth = 50) +
  scale_x_continuous(limits = c(0, 15000)) +
  scale_y_log10()


wildschwein_BE |>
  filter(year(DatetimeUTC) == 2014) |>
  ggplot(aes(DatetimeUTC, timelag, colour = TierID)) +
  geom_line() +
  geom_point()




# task_3.R
################################################################################


distance_by_element <- function(x, y){
  as.numeric(
    st_distance(x, y, by_element = TRUE)
  )
}

wildschwein_BE <- wildschwein_BE |>
  group_by(TierID) |>
  mutate(
    steplength = distance_by_element(lead(geometry), geometry)
  )




# task_4.R
################################################################################


wildschwein_BE <- wildschwein_BE |>
  group_by(TierID) |>
  mutate(
    speed = steplength/timelag
  )

Exercise B

# task_1.R
################################################################################


caro <- caro |>
  mutate(
    timelag = difftime_secs(lead(DatetimeUTC), lag(DatetimeUTC)),
    steplength = distance_by_element(lead(geometry), lag(geometry)),
    speed = steplength / timelag
  )




# task_2.R
################################################################################



caro <- caro |>
  mutate(
    timelag2 = difftime_secs(lead(DatetimeUTC,2), lag(DatetimeUTC,2)),
    steplength2 = distance_by_element(lead(geometry,2), lag(geometry,2)),
    speed2 = steplength2 / timelag2
  )




# task_3.R
################################################################################



caro <- caro |>
  mutate(
    timelag3 = difftime_secs(lead(DatetimeUTC,4), lag(DatetimeUTC,4)),
    steplength3 = distance_by_element(lead(geometry,4), lag(geometry,4)),
    speed3 = steplength3 / timelag3
  )