Exercise 5: Meets

Author

Katharina

Load libraries

library(tidyverse)
library(sf)
library(dplyr)
library(ggplot2)

Task 1: Create your own functions

  1. Calculate BMI
  2. Celsius to farenheit
  3. Euclidean distance
bmi <- function(weight_kg, heigth_m){
  weight_kg / heigth_m^2
}

bmi(70, 1.7)
celsius_to_farenheit <- function(celsius){celsius * 9/5 + 32}

celsius_to_farenheit(30)
euclidean_distance <- function(x1, y1, x2, y2){
  sqrt((x2-x1)^2 + (y2-y1)^2)
}

euclidean_distance(0,0,1,1)

Task 2: Prepare Analysis

Read in data and create the necessary sample. Convert data frame to an sfobject. Take care of the time zone!

data <- read_delim("data/wildschwein_BE_2056.csv", ",")

data_sample <- data |> 
  st_as_sf(coords = c("E", "N"), crs = 2056, remove = FALSE) |> 
  filter(
    TierName == "Rosa" | TierName == "Sabi",
    DatetimeUTC >= as.POSIXct("2015-04-01", tz="UTC"),
    DatetimeUTC < as.POSIXct("2015-04-16", tz="UTC")
  )

Task 3: Create Join Key

Round DatetimeUTC on 15 minutes.

data_sample <- data_sample |> 
  mutate(rounded_Datetime = round_date(data_sample$DatetimeUTC, "15 mins"),
         .after = DatetimeUTC)

Task 4: Measuring distance at concurrent locations

  1. Split the data_sample object into one data.frame per animal
rosa <- data_sample[data_sample$TierName == "Rosa",]
sabi <- data_sample[data_sample$TierName == "Sabi",]
  1. Join these datasets by the new rounded_Datetime column created in the last task. The joined observations are temporally close. I think inner join is the most sensible join to choose. As we join sf-objects R tells me to use st_join instead of inner_join. As st_joinautomatically joins by geometry (which is useless in this case), I need to drop the geometry before joining and use the “normal” dplyr-join.
rosa_drop <- st_drop_geometry(rosa)
sabi_drop <- st_drop_geometry(sabi)

rosa_sabi <-  
  inner_join(rosa_drop, sabi_drop, by="rounded_Datetime", suffix = c(".rosa", ".sabi"))
  1. In the joined dataset, calculate Euclidean distances between concurrent observations and store the values in a new column.
rosa_sabi <- rosa_sabi |> 
  mutate(
    distance = euclidean_distance(E.rosa, N.rosa, E.sabi, N.sabi)
    )
  1. Use a reasonable threshold on distance to determine if the animals are also spatially close enough to constitute a meet (we use 100 meters). Store this Boolean information (TRUE/FALSE) in a new column.
rosa_sabi <- rosa_sabi |> 
  mutate(
    close_100m = distance <= 100
    )

Task 5: Visualize data

Now, visualize the meets spatially in a way that you think reasonable.

ggplot() +
  geom_point(data=sabi, aes(x = E, y = N, ), color = "red", alpha=0.1) +
  geom_point(data=rosa, aes(x = E, y = N), color = "blue", alpha=0.1) +
  geom_point(data= subset(rosa_sabi, close_100m == TRUE), aes(x = E.sabi, y = N.sabi), shape=21, color = "black", fill="red") +
  geom_point(data= subset(rosa_sabi, close_100m == TRUE), aes(x = E.rosa, y = N.rosa), shape=21, color = "black", fill="blue")