提取SpatialPolygons中包含的栅格单元格数

时间:2017-04-20 15:41:39

标签: r spatial r-raster iterated-function

我想创建一个函数来计算SpatialPolygonsDataframe对象的多边形内的栅格单元数,并将该值作为新列添加而不使用循环。 我找不到怎么做......

这是我的代码:

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) 

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用功能raster::extract。默认情况下,这将提取SpatialPolygonDataFrame的每个多边形的单元格信息。输出是一个列表,以便您可以计算列表中的对象数。

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)