使用 spsample() 简化用于放置随机点的 shapefile

simplify shapefile for placing random points with spsample()

我需要使用 spsample() 在 shapefile 列表中的每个 shapefile 上放置随机点。对于一些不规则的 shapefile,这被证明是一个漫长的过程,所以我需要通过删除小的和远程的多边形来简单地处理一些 shapefile,这些多边形(我认为)是 spsample() 的麻烦制造者。

为此,我需要知道每个多边形的大小以及到所有其他多边形的平均距离。我正在寻找如何加速此计算,可能可以以更优雅(和更快)的方式完成。下面显示的尝试有效,但作为一种简化算法,它需要太多时间。

#program tries to place random points on shapefile shapes[[i]] if it fails after 300 seconds it goes though to simplifying part and swaps the old shapefile with a simplified version.

d <- shapes[[i]]
Fdist <- list()

for(m in 1:dim(d)[1]) {
      pDist <- vector()
      for(n in 1:dim(d)[1]) { 
        pDist <- append(pDist, gDistance(d[m,],d[n,]))
      }

      Fdist[[m]] <- pDist
      d@data$mean[m]<-mean(Fdist[[m]])
      d@data$gArea[m]<-gArea(d[m,])
    } 

#drop small and remote polygons

d.1<-d[d@data$gArea>=quantile(d@data$gArea, prob = seq(0, 1, length=11), type=5)[[1]] & (d@data$mean<=quantile(d@data$mean, prob = seq(0, 1, length=11), type=5)[[10]]),]

#replace with simplified polygon

shapes[[i]]<-d.1

如有任何建议,我将不胜感激。

我会先尝试简化多边形。 rmapshaper 包中的 ms_simplify 可以大大简化您的多边形,而不会引入滑动多边形或间隙:

library("rgdal")
library("rmapshaper")

big <- readOGR(dsn = ".", "unsimplified_shapefile")
big_sample <- spsample(big, 1000, type = "stratified")

small <- rmapshaper::ms_simplify(big, keep = 0.01)
small_sample <- spsample(small, 1000, type = "stratified")

使用我必须处理的 shapefile,我将 ~100MB 的 shapefile 减少到 ~2MB,并将采样时间从 ~2.3s 减少到 ~0.11s。

如果无法简化,您可以使用 byid = TRUE:

向量化 gArea()gDistance() 函数
library("rgeos")
big@data$area <- gArea(big, byid = TRUE)
big@data$dist <- gDistance(big, byid = TRUE)