2

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.

1

What you are trying to accomplish, i.e., summing pixel values from a raster based on an overlaying vector polygon is called in GIS: Zonal Statistics.

In R, one can use the extract function for this. For example:

extract(r, W, fun=sum, na.rm=TRUE)

About excluding NA pixels from the raster object, it is what Spacedman's answer said (also in Remove NA from Raster Layer) one can't actually remove such pixels to get an 'irreguar shaped raster', only replacing its values. So, replacing NA values for zero in a masked raster would also work if one just wanted to sum all values in it. See Replace NA's with 0 for raster data using R?.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.