Search code examples
rfor-looprandomr-sfterra

Generating random points within sub geometries using st_sample from the sf package


Basically I'm trying to create 5 random spatial points within polgons of a shapefile. I am trying to use st_sample() from the sf package, but am having trouble with my for loop.

Example:

library(terra)
library(sf)

#10 polygons
v <- vect(system.file("ex/lux.shp", package="terra"))
v <- v[c(1:10)] 

#Empty list to store values
empty_list <- list()

#for loop
for(i in 1:length(v$ID_1)){
  
  empty_list[i] <- st_sample(x = v[i,], size = 5, 
                             type = "random", exact =T, by_polygon = T)
}

The loop seems fairly simple and straightforward. I think the issue is that st_sample() is only storing 1 value with each iteration. Should I use something other than a list to store output values, or is a for loop not the correct option here?


Solution

  • No need to perform a for loop. You only need to specify a vector for the size argument of the st_sample() function.

    I don't know why you want to start with a SpatVector but I also gave you the code to convert the object to an sf class object because the st_sample() function expects an sf or sfc class object

    So please, find the reprex below.

    Reprex

    • Code
    library(terra)
    library(sf)
    
    # Convert 'SpatVector' into 'sf' object
    v_sf <- st_as_sf(v)
    
    # Create the random points (here, 5 random points for each polygon)
    set.seed(452)
    points <- st_sample(v_sf, size = c(5,5), type = "random")
    
    • Output
    plot(st_geometry(v_sf))
    plot(points, pch = 20, add= TRUE)
    

    Created on 2021-11-23 by the reprex package (v2.0.1)