我想从一个区域创建一些样本点。这些点必须给人一种密度的印象。我希望它们不是随机的,以避免人们认为它们是“真实的”观察。我想让它们在整个区域呈六边形分布。如何获得这样的样本呢?使用type = "hexagonal"的st_sample不能做到这一点。
一个可重复的例子:
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
# this works:
nc_samples_random <- st_sample(nc[1,], 100, type = "random")
# this does not:
nc_samples_hexagonal <- st_sample(nc[1,], 100, type = "hexagonal")最后一行代码给出了这个错误消息:
Error in seq_len(nrow(xy)) : argument must be coercible to non-negative integer任何帮助都是非常感谢的!
发布于 2019-12-13 20:11:51
编辑:请参阅底部的上一个答案
我认为st_sample source code上有一个bug。对于未投影的形状(例如,EPSG:4326),面积是以米为单位计算的,而bbox限制是以经度和纬度为单位的,这给出了问题中描述的例外情况。
只要你能很好地投射你的形状,你就能实现你的目标。在这一点上,似乎在st_sample上有一定程度的随机性,所以如果你需要一个确切的点数,你可以玩seed来获得正确的数字。
library(sf)
library(units)
nc <- st_read(system.file("shape/nc.shp", package = "sf"))
# Project shape
nc_3857 = st_transform(nc[1, ], 3857)
#Reduce a little bit via negative buffer to avoid dots on the edge
nc_3857_red = st_buffer(nc_3857, dist = set_units(-2, "km"))
#Seed and sample
set.seed(2421)
nc_samples_hexagonal <-
st_sample(nc_3857_red, 100, type = "hexagonal")
nc_unproj = st_transform(nc_3857, 4326)
nc_samples_hexagonal_unproj = st_transform(nc_samples_hexagonal, 4326)
plot(st_geometry(nc_unproj))
plot(st_geometry(nc_samples_hexagonal_unproj), add = T)
title(main = paste("N Dots Grid =", length(nc_samples_hexagonal)))

上一个答案W/替代方法
用st_make_grid实现非随机六边形点采样的另一种方法
library(sf)
nc <- st_read(system.file("shape/nc.shp", package = "sf"))
# Hexagonal grid
nc_samples_hexagonal = st_make_grid(nc[1,],
what = "corners",
square = F,
n = 20)
# Extra: Shrink original shape to 95% to erase dots close to the edge
polys = st_geometry(st_cast(nc[1,] , "POLYGON"))
cntrd = st_geometry(st_centroid(polys))
polyred = (polys - cntrd) * 0.95 + cntrd
st_crs(polyred) <- st_crs(nc[1,])
nc_samples_hexagonal = nc_samples_hexagonal[st_contains(polyred, nc_samples_hexagonal, sparse = F)]
plot(st_geometry(nc[1,]))
plot(st_geometry(nc_samples_hexagonal) , add = T)

密度可以通过reprex n=20中的cellsize或n参数进行调整。
https://stackoverflow.com/questions/59208954
复制相似问题