创建包含特定栅格值的多边形

时间:2017-07-11 21:24:00

标签: r spatial raster

我在光栅堆栈中包含4个栅格图层,并且想要生成包含指定值的所有单元格的多边形。

raster包可用于生成示例数据集。

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)

与下面的光栅一样,我的真实数据类似于动物栖息地的地图,并且有一个不完整的“好”的分布。并且&#39;坏&#39;领域

enter image description here

为了更准确地反映我的实际数据,我们可以为其他三个栅格添加一些变化并制作堆栈。

s <- stack(r, r+250, r-250, r+100)

使用堆栈s是否可以创建围绕所有堆栈层中小于300的所有单元格的多边形?

作为扩展,我的最终目标是计算生成的多边形之间的面积(或百分比)重叠。

任何建议(特定或一般)将不胜感激。

1 个答案:

答案 0 :(得分:1)

由于您正在使用栅格堆栈,因此所有单元格都应具有相同的区域。在这种情况下,我认为你根本不需要使用多边形。 (请注意,我稍微调整了您的示例数据。)

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
s <- stack(r, r + 50, r - 50, r + 100)

# Create a new raster stack with results of a logical test
s2 <- s < 300

# Create a raster indicating which cells of the new stack
# have values that are all TRUE
r2 <- sum(s2) == length(unstack(s2))
# Multiply by the area of a single cell
r3 <- r2 * area(r2)[1]

# Sum the area for all raster values
sum(values(r3), na.rm = TRUE)
## 124800

如果你想使用多边形并且你的栅格不是太大,那么将堆栈转换为SpatialPolygonsDataFrame应该非常快。这是一个产生相同结果的类似方法:

# Create a new raster stack with results of a logical test
s2 <- s < 300

# Convert to sp object
spdf <- as(s2, "SpatialPolygonsDataFrame")

# Index to the rows/features where the values in s2 were all TRUE
spdf2 <- spdf[which(rowSums(spdf@data) == length(unstack(s))), ]

rgeos::gArea(spdf2)
## 124800