问题
I would like to create a function to count the number of raster cells within the polygons of a SpatialPolygonsDataframe object and adding the value as a new column without using a loop. I cannot find how to do it...
Here is my code:
library(sp)
library(raster)
# Create a SpatialPolygonsDataframe and a raster objets to overlay
# Polygons
p1 <- rbind(c(-180,-20), c(-140,55), c(-50, 0), c(-140,-60), c(-180,-20))
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
polys <- as(spPolygons(p1, p2, p3), "SpatialPolygonsDataFrame")
# Raster
p4 <- rbind(c(-180,10), c(0,90), c(40,90), c(145,-10),
c(-25, -15), c(-180,0), c(-180,10))
rpol <- spPolygons(p4)
r <- raster(ncol=90, nrow=45)
grd <- rasterize(rpol, r, fun=sum)
# Function to count the share of occupied cells per polygon
myFunction <- function(polys,grd){
over <- crop(mask(grd, polys), polys)
share <- length(over[!is.na(over)]) / ncell(over) * 100
return(share)
}
myFunction(polys,grd)
Thanks a lot for your help!
回答1:
You can use function raster::extract
. By default, this extracts the cell info for each polygon of the SpatialPolygonDataFrame. The output is a list, so that you can count the number of objects in the list.
library(sp)
library(raster)
# Create a SpatialPolygonsDataframe and a raster objets to overlay
# Polygons
p1 <- rbind(c(-180,-20), c(-140,55), c(-50, 0), c(-140,-60), c(-180,-20))
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
polys <- as(spPolygons(p1, p2, p3), "SpatialPolygonsDataFrame")
# Create raster
r <- raster(ncol=90, nrow=45)
values(r) <- 1:ncell(r)
# Extract values
r.ext <- extract(r, polys)
# Count number of cell for each polygon
lengths(r.ext)
来源:https://stackoverflow.com/questions/43524140/extract-number-of-raster-cells-included-in-a-spatialpolygons