I have an object of class SpatialPolygonsDataFrame, and for each polygon in the dataframe I have a number of points I would like to generate in that polygon (e.g. I have 130 polygons, and I have a column of 130 integers ranging from 0-10).

Is there a way with sp (or with spatstat, sf, etc.) to generate a random pattern in each polygon using the integer number associated with that polygon?

  • You could use spsample() to generate a spatially random sample: spsample(x = polygon, n = polygon$integer, type = "random") Sep 12, 2019 at 20:46

1 Answer 1


For sp objects, you need to iterate over the features and call spsample for each one with the right number of points to generate. Here's a one-liner given a spatial polygons data frame with column npts:

p = do.call(

The returned spatial points data frame records which polygon feature each point came from:

> table(p$srcpoly)

   1    2    3    4 
   1   10  100 1000 

which is from my test set:

enter image description here

The corresponding function in the sf for sf class objects is vectorised over n, so you do:

> pp = st_sample(polys, polys$npts, "random")

but you don't get back which polygon each point comes from without doing an st_intersection (or similar) function.

  • Perfect! The second code (sf) worked perfectly. Thank you! Sep 12, 2019 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.