library(tidyverse)
library(sf)
library(dplyr)
library(ggplot2)Exercise 5: Meets
Load libraries
Task 1: Create your own functions
- Calculate BMI
- Celsius to farenheit
- 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
- Split the
data_sampleobject into onedata.frameper animal
rosa <- data_sample[data_sample$TierName == "Rosa",]
sabi <- data_sample[data_sample$TierName == "Sabi",]- Join these datasets by the new
rounded_Datetimecolumn created in the last task. The joined observations are temporally close. I think inner join is the most sensible join to choose. As we joinsf-objectsR tells me to usest_joininstead ofinner_join. Asst_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"))- 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)
)- 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")