The example data from Jeffrey
library(raster)
r <- raster(ncols=10, nrows=10)
set.seed(0)
x <- runif(ncell(r))
x[round(runif(25,1,100),digits=0)] <- NA
r[] <- x
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
polys <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), Polygons(list(Polygon(cds2)), 2)))
polys <- SpatialPolygonsDataFrame(polys, data.frame(ID=sapply(slot(polys, "polygons"), function(x) slot(x, "ID"))))
Now use extract
extract(r, polys, fun=function(x, ...) length(na.omit(x))/length(x))
#[1] 0.8333333 0.6666667
If you have many rasters, first use stack to combine them (if they have the same extent and resolution)
To get the actual polygon area you should not use the slot(i, 'area') approach.
For planar data you can use rgeos::gArea(polys, byid=TRUE)
For spherical data (lon/lat) you can use geosphere::areaPolygon
Best Answer
You can use a conditional statement. The issue with previous recommendations is that when you rasterize your polygons (which is necessary) the background, that does not contain polygons, will be NoData resulting in corresponding areas in the output also being NoData. You will need to set your analysis extent to your original raster and then set a background value (i.e., 0) to the rasterized polygon raster using SetNull. Once you have done this a conditional statement in the raster calculator will look something like this.
Con("praster" > 0, "praster", "OrgRaster")
"praster" is your rasterized ploygon feature class, with a background value of 0, and "OrgRaster" is the raster you wish to modify. This statement is saying that if praster is greater than 0 then assign values from praster else assign values from OrgRaster.