R-空间聚合物中包含的栅格单元的提取数量



我想创建一个函数来计算空间polygonsdataframe对象的多边形内的栅格单元的数量,并在不使用循环的情况下将值添加为新列。我找不到如何做...

这是我的代码:

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) 

非常感谢您的帮助!

您可以使用函数raster::extract。默认情况下,这会提取空间polygondataframe的每个多边形的单元格信息。输出是列表,因此您可以计算列表中的对象数量。

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)

值得注意的是,使用terra可以更快地执行此操作。就我而言,运行类似的东西的速度约为80倍:

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")
r <- raster(ncol=90, nrow=45)
values(r) <- 1:ncell(r)
v <- terra::vect(polys)
r <- terra::rast(r)
cells_per_poly <- terra::extract(r, v) %>% group_by(ID) %>% summarise(n=n())

相关内容

  • 没有找到相关文章

最新更新