Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random locations along the outer border of a .shp polygon using R

I am able to generate random points within the polygons using the package sp, however I am interested in generating points along the outline of the polygon.

For example, if I have a shapefile of a lake I can use spsample(lake,n=10,type="random") to generate 10 random locations within this lake. I am looking to do a similar thing but instead of generating the locations within the lake, I want the points to simply be along the shoreline. Is there a simple way to do this that I am just missing?

like image 644
mchen Avatar asked Oct 28 '25 14:10

mchen


1 Answers

If you are willing to use the sf package, you can use the st_sample function. The trick is to first convert the polygon into a line, then sample the points.

library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(ggplot2)
set.seed(415)

# read polygon shapefile
nc_p <- st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)[1, 1]

# Convert to line
nc_l <- st_cast(nc_p, 'MULTILINESTRING')

# sample points along line
nc_s <- st_sample(nc_l, 10)
#> although coordinates are longitude/latitude, st_sample assumes that they are planar

ggplot() +
  theme_void() +
  geom_sf(data = nc_p, fill  = 'grey') +
  geom_sf(data = nc_l, color = 'red') +
  geom_sf(data = nc_s, color = 'blue')

Created on 2021-08-30 by the reprex package (v2.0.0)

like image 100
nniloc Avatar answered Oct 30 '25 05:10

nniloc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!