如何计算栅格到最近多边形的距离?

问题描述

我有一个空的光栅文件 (r1,Rasterlayer),我想计算每个非 NA 单元格到最近多边形 (S1,SpatialpolygonsDataFrame)。 r1S1 均以 utm 投影。是否有任何 R 包可以做到这一点?

解决方法

可以先光栅化,再用距离。

library(raster)
p1 <- rbind(c(-180,-20),c(-140,55),c(10,0),-60),c(-180,-20))
pols <- spPolygons(p1)
r <- raster(ncol=90,nrow=45)
r <- rasterize(pols,r)

d <- distance(r)

(奇怪的外观模式是因为光栅具有环绕日期线的经纬度坐标)

,

您可以使用 distance 中的 library(raster) 函数,该函数返回所有 NA 单元格到最近的非 NA 单元格的距离:

install.packages('raster')
library(raster)

distance(r1,S1,filename = 'raster_distance',doEdge= TRUE)
,

这也是我想在一次性函数中找到的东西 - 类似于 raster::distance 但告诉您每个单元格最接近哪个多边形,通过 ID 字段或类似的。

Annyhoo,暂时;

# make a dummy raster with some dummy data. 
r <- raster(xmn = 50,xmx = 80,ymn = -7,ymx = 10,res=0.5)
r[] <- sample(1:10,ncell(r),replace=T)

# make some dummy polygons that you want to know the min distance to on your raster
p1 <- rbind(c(55,-5),c(65,c(55,-5))
p2 <- rbind(c(70,c(75,2),c(70,-5))
p3 <- rbind(c(55,4),7),4))
pols <- st_as_sf(spPolygons(p1,p2,p3))
pols$ID <- 1:3

# let's look
plot(r)
plot(pols$geometry,add=T)

enter image description here

# to make a raster layer of min euclidean distance to a polygon (any),# loop through the sf ID's and `fasterize` (v. quick) and run the 
# raster::distance function to find out the distance from itself

st <- stack()

for(i in pols$ID){
  r_pol <- fasterize(pols[pols$ID==i,],r,field="ID")
  rd <- distance(r_pol)
  st <- stack(st,rd)
}

# To produce a simple min distance from any polygon,just select the min from the stack
r_min_dis_any_pol <- min(st)
plot(r_min_dis_any_pol)

enter image description here

# to go a bit further and let you know to which polygon the min distance refers to
r_min_which_pol <- which.min(st)
plot(r_min_which_pol)

enter image description here

# if you were interested in a zonal sum of the raster data,dependent on its nearest polygon

zonal_sum <- zonal(r,r_min_which_pol,fun="sum")

identical(sum(zonal_sum[,2]),cellStats(r,sum))
[1] TRUE