[R-sig-Geo] Extracting raster weighted mean without NAs

Stachelek, Joseph jstachel at sfwmd.gov
Wed Sep 24 16:14:27 CEST 2014

I think you can avoid returning NA if you use the example code for extract with polygons with weights but change the last two lines to:

v <- extract(r, polys, weights=TRUE)
sapply(v, function(x) sum(apply(x, 1, prod),na.rm=T) / sum(x[,2],na.rm=T))

-----Original Message-----
From: r-sig-geo-bounces at r-project.org [mailto:r-sig-geo-bounces at r-project.org] On Behalf Of Arnaud Mosnier
Sent: Wednesday, September 24, 2014 9:59 AM
To: r-sig-geo at r-project.org; Robert Hijmans
Subject: [R-sig-Geo] Extracting raster weighted mean without NAs


I need to extract the mean value of raster values into several
I use the extract function from the raster package with the weight option
in order to take into account the area of each raster cell with data
included into each polygon.
However, I want to make the calculation even if some cells contain NAs,

Here is a small code to explain my case:

mat <- matrix(rep(c(4,5,3,2,1), 5), ncol=5)
r <- raster(mat)
r[2,4] <- NA
corners1 <- rbind(c(0.2,0.1), c(0.2,0.7), c(0.4, 0.7), c(0.4,0.1),
corners2 <- rbind(c(0.7,0.1), c(0.7,0.7), c(0.9, 0.7), c(0.9,0.1),
polys <- SpatialPolygons(list(Polygons(list(Polygon(corners1)), ID="1"),
Polygons(list(Polygon(corners2)), ID="2")))
plot(polys, add=T)

extract(r, polys, weight=TRUE, fun=mean, na.rm=TRUE, small=TRUE)

>[1] 2.666667       NA

Note: The use of the parameter na.rn=TRUE does not resolve my issue.

Any workaround ?



        [[alternative HTML version deleted]]

R-sig-Geo mailing list
R-sig-Geo at r-project.org

We value your opinion. Please take a few minutes to share your comments on the service you received from the District by clicking on this link<http://my.sfwmd.gov/portal/page/portal/pg_grp_surveysystem/survey%20ext?pid=1653>.

More information about the R-sig-Geo mailing list