library(tidyverse)
library(mapview)
library(sf)
library(tmap)
library(RColorBrewer)
library(rnaturalearth)
load("Exploratory_maps.rda")

How many observations of each species are found in each landcover?

This question forms a simple start to any analysis. Before going on to answer it we might consider an issue that could confound the analysis. Some of the landcover types cover a much larger area than others. So we might expect many more counts in these than in the land cover types which cover a small area. We could calculate what percentage of the total study area falls into each class.

habitat %>% mutate(percent=round((Area/sum(Area))*100,1)) ->habitat

Now to find which cover class each bird observation fall into we simply join the two objects and drop the geometries.

birds %>% st_join(habitat) %>% st_drop_geometry() -> joint

Now we can summarise the data by counting up all the combinations of species and cover class.

joint %>% group_by(LandCover,Species) %>% summarise(n=n(),percent=min(percent)) ->table1

Now the expected number of counts of each species in each class would be the total number of counts of the species multiplied by the proportion of the area that falls into the cover class. If there are more counts than expected this may suggest that species prefers this type of habitat.

table1 %>% group_by(Species) %>% mutate(expected=round(sum(n)*(percent/100))) %>% mutate(difference=n-expected) -> table1
aqm::dt(table1)
table1$Species<-as.factor(table1$Species)
filter(table1,Species=="House Sparrow") ->hs
hs$LandCover<-fct_reorder(hs$LandCover,hs$difference, min) 
ggplot(hs,aes(x=LandCover,y=difference)) +geom_col() +coord_flip()