I have two raster objects in R with 216 grids or cells with the same longitude and latitude coordinates, one with values of daily maximum wind speeds per grid and one with numbers representing a population count in an individual grid. The first raster has 183 layers and is represented by the information below.
> CMAWRF[[1]]
class : SpatRaster
dimensions : 12, 18, 183 (nrow, ncol, nlyr)
resolution : 0.25, 0.25 (x, y)
extent : 3.125, 7.625, 50.625, 53.625 (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84
source : IPSL-IPSL-CM5A-MR_r1i1p1_IPSL-WRF381P1980.nc
varname : sfcWindAdjust (Bias-Adjust Near-Surface Wind Speed)
names : sfcWi~ust_1, sfcWi~ust_2, sfcWi~ust_3, sfcWi~ust_4, sfcWi~ust_5, sfcWi~ust_6, ...
unit : m s-1, m s-1, m s-1, m s-1, m s-1, m s-1, ...
time : 1980-01-01 10:30:00 to 1980-12-31 10:30:00
The second raster only has 1 layer and has the same extent. As one might notice, the latitude coordinates are from 3.125 to 7.625 and the longitude coordinates are from 50.625 to 53.625. These coordinates encapsulate The Netherlands.
So my goal is to multiply each I,Jth (I for row, J for column) cell value from the population raster with each I,Jth cell value from the wind speed raster for each layer. However, I only want to do this for the cell values that are within the country borders of the Netherlands, so not the whole region covered by the spatial raster.
Does anyone know how to do this in R?
Example data
library(terra)
nld <- geodata::gadm("NLD", level=0, path=".")
pop <- rast(ext(nld) + 2, res=.1)
values(pop) <- 1:ncell(pop) / 100
wth <- rast(pop, nlyr=2)
values(wth) <- runif(size(wth))
Solution
r <- mask(pop, nld, updatevalue=1)
x <- wth * r
plot(x, fun=\()lines(nld))