gpt4 book ai didi

r - 提取 SpatialPolygons 中包含的栅格像元数

转载 作者:行者123 更新时间:2023-12-04 12:47:26 24 4
gpt4 key购买 nike

我想创建一个函数来计算 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)

非常感谢您的帮助!

最佳答案

您可以使用函数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)

关于r - 提取 SpatialPolygons 中包含的栅格像元数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com