I have masked and cropped a raster based on a country boundary as follows:
library(geodata)
library(terra)
tmax <- worldclim_global("tmax", 2.5, path=tempdir())
tmax_yr <- tmax[[1]]
mys <- gadm(country="MYS", level=1, path=tempdir())
mys <- terra::project(mys, crs(tmax_yr))
tmax_crop <- terra::crop(tmax_yr, mys, mask = TRUE)
plot(tmax_crop)
plot(mys, add = T)
If I zoom into a small section of the image shown below, I can see the edges of the country boundary has jagged image i.e. raster cells are not smooth. Is there any to smooth them out so that raster cells are not protruding out from the polygon boundary?
P.S. I noticed the snap
argument in the crop
function but there's no description of what it does in the documentation
CodePudding user response:
You are dealing with raster data. By definition, the edges are not smooth. But the higher the spatial resolution, the less noticeable. You could download the climate data at a 30s spatial resolution. That is a 5x5=25 times higher spatial resolution.
If this is only for the aesthetics, you could also first crop the the data you are using, then disaggregate (e.g. with a factor of 5), and mask. Like this:
library(geodata)
library(terra)
tmax <- worldclim_global("tmax", 2.5, path=tempdir())
mys <- gadm(country="MYS", level=1, path=tempdir())
x <- crop(tmax[[1]], mys)
x <- disagg(x, 5)
x <- mask(x, mys)
plot(x)
CodePudding user response:
Looking at the documentation for terra::crop
, there is an argument called touches
that includes cells touched by lines or polygons. It makes it so that it would not go outside the lines.
tmax_crop <- terra::crop(tmax_yr, mys, touches = F, mask = T)