1

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") – JepsonNomad Sep 12 at 20:46
2

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(
      rbind,
      lapply(
        1:nrow(polys),
        function(i){
          SpatialPointsDataFrame(
            spsample(polys[i,],
                     n=polys$npts[i],
                     type="random"), 
            data=data.frame(srcpoly=rep(i,polys$npts[i]))
           )
         }
        )
        )

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! – James Fischer Sep 12 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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