Load all the shapefiles into one spatial object

library(sf)
library(rgdal)
library(raster)
library(leaflet.extras)
library(dplyr)
fls<-dir(path="/home/rstudio/markus/shapefiles", pattern="*shp$")
fls<-sprintf("/home/rstudio/markus/shapefiles/%s",fls)
f1<-sf:::read_sf(fls[1])

library(mapview)
f<-function(x){
  out<-read_sf(x)
  out<-out[,c("MALE","geometry")]
  out$filename<-x
  out

}
territories<-lapply(fls,f)
d<-do.call("rbind",territories)
d$year<-gsub("[^0-9]","",d$filename)
d$year<-as.numeric(d$year)

View

As the number of years would lead to a confusing map if I plotted all together I’ll separate them into blocks.

Up to 2010

Go full screen and select years to view.

d %>% filter(year<2010) %>%
mapview(zcol="year",burst=TRUE) ->m
m@map %>% addFullscreenControl()

2010 and later

Go full screen and select years to view.

d %>% filter(year>2009) %>%
mapview(zcol="year",burst=TRUE) ->m
m@map %>% addFullscreenControl()
dsm<-raster("/home/rstudio/markus/MonksCut_CHM.tif")
#str(dsm)
#mapview(dsm)

cells<-sf:::read_sf("/home/rstudio/markus/MonksCells_Attributes.shp")

#mapview(cells)

Load layers into Postgis

The following will load the two shapefiles into a database on the server called monkswood.

library(RPostgreSQL) 
conn = dbConnect(PostgreSQL(), dbname = "monkswood",host="postgis",pass="docker",user="docker")

#dbSendQuery(conn,"create extension postgis")
#dbSendQuery(conn,"create extension plr")
d %>% st_cast("POLYGON") -> d
## Warning in st_cast.MULTIPOLYGON(X[[i]], ...): polygon from first part only
d$gid<-as.numeric(rownames(d))
st_write_db(conn,d,table="territories",drop = TRUE)
cells$gid<-as.numeric(rownames(cells))
st_write_db(conn,cells,table="cells",drop = TRUE)
dbDisconnect(conn)
## [1] TRUE
PgLoadRaster<-function(flnm="MonksCut_CHM.tif",x=100,y=100,tabnm="chm",db="monkswood",srid=27700,path="/home/rstudio/markus/"){
flnm<-paste(path,flnm,sep="")  
command <- paste("export PGPASSWORD='docker'; raster2pgsql -s ",srid, "-I -d  -M  ",flnm, " -F -t ",x,"x",y," ",tabnm,"|psql -h postgis -U docker -d ",db,sep="")
system(command)
}

PgLoadRaster()
conn = dbConnect(PostgreSQL(), dbname = "monkswood",host="postgis",pass="docker",user="docker")
test<-st_read_db(conn,query="select * from territories")
mapview(test)
dbDisconnect(conn)
## [1] TRUE