week6_my_solutions

PrePro

pacman::p_load("sf", "dplyr", "ggplot2", "spatstat.geom", "spatstat.explore",
  "gstat", "tidyr", "terra", "tmap","readr")

wildschwein_BE <- read_delim("wildschwein_BE_2056.csv", ",") |>
    st_as_sf(coords = c("E", "N"), crs = 2056, remove = FALSE)
Rows: 51246 Columns: 6
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (2): TierID, TierName
dbl  (3): CollarID, E, N
dttm (1): DatetimeUTC

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Task 1: Import and visualize spatial data

feldaufnahmen <- read_sf("Feldaufnahmen_Fanel.gpkg")

What information does the dataset contain? What is the geometry type of the dataset (possible types are: Point, Lines and Polygons)? What are the data types of the other columns? What is the coordinate system of the dataset?

st_layers("Feldaufnahmen_Fanel.gpkg") #One Layer
Driver: GPKG 
Available layers:
           layer_name geometry_type features fields       crs_name
1 Feldaufnahmen_Fanel       Polygon      975      2 CH1903+ / LV95
st_crs(feldaufnahmen) #CH1903+ / LV95
Coordinate Reference System:
  User input: CH1903+ / LV95 
  wkt:
PROJCRS["CH1903+ / LV95",
    BASEGEOGCRS["CH1903+",
        DATUM["CH1903+",
            ELLIPSOID["Bessel 1841",6377397.155,299.1528128,
                LENGTHUNIT["metre",1]]],
        PRIMEM["Greenwich",0,
            ANGLEUNIT["degree",0.0174532925199433]],
        ID["EPSG",4150]],
    CONVERSION["Swiss Oblique Mercator 1995",
        METHOD["Hotine Oblique Mercator (variant B)",
            ID["EPSG",9815]],
        PARAMETER["Latitude of projection centre",46.9524055555556,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8811]],
        PARAMETER["Longitude of projection centre",7.43958333333333,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8812]],
        PARAMETER["Azimuth of initial line",90,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8813]],
        PARAMETER["Angle from Rectified to Skew Grid",90,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8814]],
        PARAMETER["Scale factor on initial line",1,
            SCALEUNIT["unity",1],
            ID["EPSG",8815]],
        PARAMETER["Easting at projection centre",2600000,
            LENGTHUNIT["metre",1],
            ID["EPSG",8816]],
        PARAMETER["Northing at projection centre",1200000,
            LENGTHUNIT["metre",1],
            ID["EPSG",8817]]],
    CS[Cartesian,2],
        AXIS["(E)",east,
            ORDER[1],
            LENGTHUNIT["metre",1]],
        AXIS["(N)",north,
            ORDER[2],
            LENGTHUNIT["metre",1]],
    USAGE[
        SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],
        AREA["Liechtenstein; Switzerland."],
        BBOX[45.82,5.96,47.81,10.49]],
    ID["EPSG",2056]]
feldaufnahmen #Polygon, Feldnummer mit Fruchttyp
Simple feature collection with 975 features and 2 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 2568099 ymin: 1199766 xmax: 2578824 ymax: 1207836
Projected CRS: CH1903+ / LV95
# A tibble: 975 × 3
   FieldID Frucht                                                           geom
     <dbl> <chr>                                                   <POLYGON [m]>
 1       1 Roggen ((2570914 1202743, 2570917 1202749, 2570985 1202833, 2571294 …
 2       0 <NA>   ((2570893 1202758, 2570893 1202758, 2570959 1202845, 2570985 …
 3       0 <NA>   ((2570868 1202776, 2570872 1202781, 2570913 1202828, 2570946 …
 4       2 Wiese  ((2570882 1203234, 2570641 1202974, 2570630 1202983, 2570606 …
 5       3 Weide  ((2570249 1203116, 2570371 1203328, 2570481 1203197, 2570390 …
 6       5 Weide  ((2570378 1203320, 2570466 1203436, 2570552 1203289, 2570481 …
 7       6 Weide  ((2570466 1203436, 2570572 1203495, 2570659 1203433, 2570659 …
 8       4 Weide  ((2569706 1203278, 2569706 1203342, 2570199 1203198, 2570223 …
 9       7 Wiese  ((2570804 1203310, 2570805 1203312, 2570900 1203608, 2571208 …
10       0 Wald   ((2571004 1202990, 2571041 1203029, 2571073 1203003, 2571035 …
# ℹ 965 more rows

verfiy visually that the two geodatasets are aligning

tm_shape(feldaufnahmen) +
  tm_polygons(col = "Frucht") +
tm_shape(wildschwein_BE) +
  tm_symbols(size = 0.2)+
  tm_layout(legend.position = c("right", "center"))
Warning: Number of levels of the variable assigned to the aesthetic "col" of
the layer "polygons" is 44, which is larger than n.max (which is 30), so levels
are combined.
[plot mode] fit legend/component: Some legend items or map compoments do not
fit well, and are therefore rescaled.
ℹ Set the tmap option `component.autoscale = FALSE` to disable rescaling.

Task 2: Annotate Trajectories from vector data

wildschwein_join <- st_join(wildschwein_BE,feldaufnahmen)

Task 3: Explore annotated trajectories

library("lubridate")

Attaching package: 'lubridate'
The following objects are masked from 'package:terra':

    intersect, union
The following objects are masked from 'package:base':

    date, intersect, setdiff, union
library("forcats")
wildschwein_smry<- wildschwein_join |> 
  st_drop_geometry() |> 
  mutate(
    hour=hour(round_date(DatetimeUTC,"hour")),
    Frucht=fct_lump(Frucht,3)) |> 
  group_by(TierName,hour,Frucht) |> 
  summarise(n=n()) |> 
  group_by(TierName,hour) |> 
  mutate(perc = n/sum(n)*100)
`summarise()` has grouped output by 'TierName', 'hour'. You can override using
the `.groups` argument.

visualize the percentage of samples in a given crop per hour.

wildschwein_smry |> 
  ggplot(aes(hour, perc, fill=Frucht))+
  geom_col()+
  facet_wrap(~TierName)+
  scale_y_continuous(
    labels = scales::label_number(suffix = "%"))+
  labs(
    x = "Time (rounded to the nearest hour)",
    y = "Percentage",
    title = "Percentages of samples in a given crop per hour",
    subtitle = "(Only showing the most common categories)"
  )

Task 4: Import and visualize vegetationindex (raster data)

veg <- rast("vegetationshoehe_LFI.tif")
plot(veg)

Task 5: Annotate Trajectories from raster data

wildboar_veg<- extract(veg, vect(wildschwein_BE))
Warning: [extract] transforming vector data to the CRS of the raster
nrow(wildboar_veg)
[1] 51246
nrow(wildschwein_BE) #gleiche Anzahl Spalten
[1] 51246
wildschwein_BE$veg <- wildboar_veg$vegetationshoehe_LFI

mean vegetation height per hour and TierName

library(dplyr)
library(lubridate)

wildschwein_smry_veg <- wildschwein_BE |>
  st_drop_geometry() |>
  mutate(
    hour = hour(round_date(DatetimeUTC, "hour"))
  ) |>
  group_by(TierName, hour) |>
  summarise(
    veg_avg = mean(veg, na.rm = TRUE),
    .groups = "drop"
  )

visualize

library(ggplot2)

wildschwein_smry_veg |>
  ggplot(aes(x = hour, y = veg_avg, fill = TierName)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~TierName) +
  labs(
    x = "Time (rounded to the nearest hour)",
    y = "Mean vegetation height [m]",
    title = "Vegetation height per animal and hour"
  )