I can not reproduce your code, but allow me to illustrate the approach on a similar use case; I have used temperature data from Copernicus and cropped it to shape of the Czech Republic from GADM.
This approach requires only two packages (raster
and sf
) + tidyverse
, just because :))
It uses two steps:
- remove the extra data points via
raster::mask()
- crop the file down to size via
raster::crop()
library(tidyverse) # because tidyverse :)
library(raster) # raster spatial data processing
library(sf) # vector spatial data processing
data <- raster("./src/tg_0.25deg_day_2019_grid_ensmean.nc") # your ncdf file
borders <- readRDS("./src/gadm36_CZE_0_sf.rds") # country borders in sf format
plot(data) # the big picture
data_masked <- mask(data,borders) %>% # mask the unwanted areas
crop(borders) # crop to shape
plot(data_masked) # the small picture