Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Created January 9, 2019 21:41
Show Gist options
  • Select an option

  • Save obrl-soil/9007f3194efb8c72c6d4fdac623d68a5 to your computer and use it in GitHub Desktop.

Select an option

Save obrl-soil/9007f3194efb8c72c6d4fdac623d68a5 to your computer and use it in GitHub Desktop.
For sampling in a buffer but only keeping points south of centre
# from https://twitter.com/RallidaeRule/status/1083102769169514497
library(sf)
options(stringsAsFactors = FALSE)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
pts <- st_centroid(nc[1:3, ])
pts <- pts[ , c('NAME')]
pts <- st_transform(pts, 32617)
buff <- st_buffer(pts, 10000)
# need northing of each point appended to buffer
# use as a filter later
buff$center_N <- st_coordinates(pts)[,2]
# make points
sample_points <- lapply(split(buff, 1:nrow(buff)), function(x) {
# generate 20 points inside the buffer poly
spts <- st_coordinates(st_sample(x, 20))
# drop the ones north of center
spts <- spts[spts[,2] < x$center_N, ]
# respatialise
st_as_sf(as.data.frame(spts), coords = c('X', 'Y'), crs = st_crs(x))
})
sample_points <- do.call('rbind', sample_points)
plot(buff[0], reset = F, axes = T)
plot(pts[0], add = T, col = 'red', pch = 19)
plot(sample_points[0], add = T, col = 'blue', pch = 19)
# \o/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment