library(raster)
## Loading required package: sp
library(sf)
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(mapSpain)
## Warning: package 'mapSpain' was built under R version 4.0.4
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.0.4
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# Shape CCAA - solo Galicia (Ejemplo)
prov <- esp_get_prov("Galicia")


# Raster de ejemplo
set.seed(1234)
values <- runif(10000,0,200)

rast <- raster(prov, nrow=100, ncol=100, vals=values)
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj
## = prefer_proj): Discarded datum Unknown based on GRS80 ellipsoid in Proj4
## definition
## Warning in showSRID(SRS_string, format = "PROJ", multiline = "NO", prefer_proj
## = prefer_proj): Discarded datum European Terrestrial Reference System 1989 in
## Proj4 definition
plot(rast)

# Shape CCAA - solo Galicia (Ejemplo)
prov <- esp_get_prov("Galicia")



prov <- st_transform(prov,st_crs(rast))
rast_crop <- crop(rast,prov)
plot(rast_crop)

# Objecto espacial
xy <- as.data.frame(coordinates(rast_crop))
out <-
  sf::st_as_sf(xy,
               coords = c("x", "y"),
               crs = sf::st_crs(rast_crop)
  )

out$alt <- getValues(rast_crop)

plot(out[,"alt"])

join <- st_join(prov,out) %>% st_drop_geometry()
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
# Altitud por provincia
join %>% 
  group_by(ine.prov.name) %>%
  summarise(m = mean(alt, na.rm=TRUE))
## # A tibble: 4 x 2
##   ine.prov.name     m
##   <chr>         <dbl>
## 1 Coruña, A     100. 
## 2 Lugo          101. 
## 3 Ourense        99.6
## 4 Pontevedra    100.