Search code examples
rshapefileraster

average raster file value in shapefile area returns multiple outputs - interpreting results


So I have my raster file

r <- raster('ras')

and a shapefile

abys <- readShapeSpatial('abys')

I calculated the mean values defined by the shapefile by the following method:

r.vals<- extract(r,abys)
r.mean <- lapply(r.vals,FUN=mean)

However, when using a couple of shapefiles when I return the output I get multiple results, e.g.:

[[1]]
[1] 9321

[[2]]
[1] 6616

[[3]]
[1] 8348

It should just return one which is what I usually get. Is this because of some characterestic of my shapefile or a problem with my methodology?

Thanks for your input


Solution

  • Your problem is that there are three polygons in abys.

    The best solution is not to average the results but to union the polygon first:

    library(rgeos)
    abys.single <- gUnaryUnion(abys)
    r.vals<- extract(r,abys.single)
    r.mean <- lapply(r.vals,FUN=mean)