R – Getting Masked Raster with No NAs and Summing Pixels Within Overlaying Polygon

missing datapolygonrrasterzonal statistics

I have done an IDW interpolation in R for precipitation data following the routine of Manny Gimond (https://mgimond.github.io/Spatial/interpolation-in-r.html) to get precipitation inside a catchment.

Here is the routine:

library(gstat) #Use gstat's idw routine
library(sp)    #Used for the spsample function

#Create an empty grid where n is the total number of cells
grd <- as.data.frame(spsample(P, "regular", n=50000))
names(grd) <- c("X", "Y")
coordinates(grd) <- c("X", "Y")
gridded(grd) <- TRUE  # Create SpatialPixel object
fullgrid(grd) <- TRUE  # Create SpatialGrid object

# Add P's projection information to the empty grid
proj4string(grd) <- proj4string(P)

# Interpolate the grid cells using a power value of 2 (idp=2.0)
P.idw <- gstat::idw(Precip_in ~ 1, P, newdata=grd, idp=2.0)

# Convert to raster object then clip to Texas
r <- raster(P.idw)
r.m <- mask(r, W)

The problem is that in the last step (i.e masking the raster with interpolated values (r) to the boundaries of the geometry of interest) a great number of NA values appear that correspond to point lying out of the masking polygon.

What I am looking for is a function to use in conjunction with mask that ensures that in the final masked raster these NA values are removed so that I have raster with no NA value.

Best Answer

What I am looking for is a function to use in conjunction with mask that ensures that in the final masked raster these NA values are removed so that I have raster with no NA value.

A raster is an NxM grid where every cell has a value. If the value is not known, it is generally set to NA (or some special value like "-9999"). There's no way you can "remove" a value from a cell without replacing it with something else.

Related Question