如何从保持其自身几何形式的某个地方提取随机坐标?

How to extract random coordinates from some place keeping its own geometric form?

我想在红色边界区域中获取随机坐标:

下面的代码是我迄今为止尝试过的代码,但我不确定这是否能达到预期的效果,因为这是一些代码的混合,而且我从未见过示例代码将随机坐标转换为此类位置的原始几何形状。

library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(dismo)
library(rgdal)
library(sf)
library(rgdal)
library(maptools)
library(scales)
d=getData('worldclim',lat=-5.49839,lon=-39.32062,res=0.5,var='bio')#these la and lon are the center coordinates
setwd('C:/Users/DAVI/Desktop/Nova pasta (2)')#My dir
estados=readShapePoly("lim_unidade_federacao_a.shp")## This is a SpatialPolygonsDataFrame keeping all states of Brazil, the download is after the question.
estados[estados@data$nome=="Ceará",]## I'm just interested about Ceara
plot(estados[estados@data$nome=="Ceará",])##Note that it keeps the geometry of the state which I'm interested in
ceara=spsample(estados[estados@data$nome=="Ceará",],n=1000,type="random")##Sampling random cordinates

这运行没有问题,但正如我所说,我不确定它是否正确。

使用的数据:https://drive.google.com/file/d/1l5dOt5l2f6DZz3dRq7p0Ig9Q1iE8BdLB/view?usp=sharing

请找到一种使用 sf 库的可能方法

代码

library(sf)

# Select 'Ceara'
Ceara <- estados %>% 
  filter(., sigla == "CE")

# Generate the random points in 'Ceara'
set.seed(452) # set seed for reproducibility
points <- Ceara %>% 
  st_sample(., size = 1000, type = "random")

# Visualization
plot(st_geometry(Ceara))
plot(points, pch = 20, add= TRUE)

输出


方案二(不推荐)

由于您似乎想使用 sprgdal 库来执行此操作,这里是完成这项工作的代码(这是我不推荐的解决方案 运行,因为 rgdal 将在不久的将来过时,请参阅 )。

您的代码的问题在于您没有使用正确的函数来读取文件:必须使用 rgdal 库中的 readOGR()。此外,我还简化了您在 sp 对象 estados

中选择 Ceara 的代码

Reprex

library(rgdal)
library(sp)

estados <- readOGR("YourPath/lim_unidade_federacao_a.shp") # use readOGR and not readShapePoly

# Select 'Ceara'
Ceara <- estados[which(estados$sigla == "CE"),] # cleaner code to select 'Ceara'

# Generate the random points in 'Ceara'
set.seed(452) # set seed for reproducibility
points <- spsample(Ceara, n = 1000, type = "random")

# Visualization
plot(Ceara)
plot(points, pch = 20, add= TRUE)

reprex package (v2.0.1)

创建于 2022-01-07