How to Generate Random Points Inside Irregular Raster Boundary Using R?

Can you generate random points inside an irregular raster boundary using R?

You, actually, can! Here is the R-code you need.

# Call st_* functions
library(sf)

# Load your raster
raster <- raster('~/path/to/raster.tif')
plot(r)

# Determine raster's edge to make sure points are within raster's study extent
edge_line <- rasterToContour(is.na(raster))

# st_union to dissolve geometries
pol <- as(st_union(st_polygonize(st_as_sf(edge_line))), 'Spatial')

# Perform the random point sampling, generate 100 points, and save .csv
random100 <- spsample(pol[1,], 100, type = 'random', iter = 1000)

xy100ran <- data.frame(random100)
names(xy100ran) <- c('x','y')
random100pts <- cbind(extract(raster, xy100ran, df = T),xy100ran)

write.csv(random100pts, file = 'C:/filename.csv')

2 thoughts on “How to Generate Random Points Inside Irregular Raster Boundary Using R?

Leave a Reply

Your email address will not be published. Required fields are marked *

five + one =

This site uses Akismet to reduce spam. Learn how your comment data is processed.