I am wondering what is the easiest way to generate random points per polygon feature using sp::spsample
so that number of points in each feature is proportional to the corresponding polygon area. I know how to do it one a polygon but I am not sure how I should do it per feature.
Sample data
p <- shapefile(system.file("external/lux.shp", package="raster"))
One way to do this is as below:
library(raster)
library(sf)
set.seed(123)
# shape file from raster package
p <- shapefile(system.file("external/lux.shp", package="raster"))
plot(p)
# Using an old fashion for-loop
rpnt <- list()
for(i in 1:length(p)){
pp <- p[p$ID_2==i,]
rpnt[[i]] <- sp::spsample(pp, n=pp$AREA/20, "random") #modify it to what you want
plot(rpnt[[i]], pch=i, col=(i), add=T)
}
out <- do.call(bind, rpnt)