mchen
mchen

Reputation: 71

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?

Upvotes: 4

Views: 303

Answers (2)

CARLOS_BEDSON
CARLOS_BEDSON

Reputation: 53

This also equivalent to "Generate points along lines" in ArcGIS - yet this R answer not easily found through google searches - please is it possible to rephrase or add to question

Upvotes: 0

nniloc
nniloc

Reputation: 4243

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)

Upvotes: 3

Related Questions