Search code examples
rspatialr-sfr-sprgdal

How to extract random coordinates from some place keeping its own geometric form?


I'd like to get random coordinates into the red bounded area:

enter image description here

The code below is what I've tried so far but I'm not sure if this does what it is supposed to do since this is a mix of a few codes and I've never seen a code which samples random coordinates into an original geometry of a such location.

library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(dismo)
library(rgdal)
library(sf)
library(rgdal)
library(maptools)
library(scales)
d=getData('worldclim',lat=-5.49839,lon=-39.32062,res=0.5,var='bio')#these la and lon are the center coordinates
setwd('C:/Users/DAVI/Desktop/Nova pasta (2)')#My dir
estados=readShapePoly("lim_unidade_federacao_a.shp")## This is a SpatialPolygonsDataFrame keeping all states of Brazil, the download is after the question.
estados[estados@data$nome=="Ceará",]## I'm just interested about Ceara
plot(estados[estados@data$nome=="Ceará",])##Note that it keeps the geometry of the state which I'm interested in
ceara=spsample(estados[estados@data$nome=="Ceará",],n=1000,type="random")##Sampling random cordinates

This runs with no problem but as I've told I'm not sure if it's right.

Data used: https://drive.google.com/file/d/1l5dOt5l2f6DZz3dRq7p0Ig9Q1iE8BdLB/view?usp=sharing


Solution

  • Please find one possible approach using the sf library

    Code

    library(sf)
    
    # Select 'Ceara'
    Ceara <- estados %>% 
      filter(., sigla == "CE")
    
    # Generate the random points in 'Ceara'
    set.seed(452) # set seed for reproducibility
    points <- Ceara %>% 
      st_sample(., size = 1000, type = "random")
    
    # Visualization
    plot(st_geometry(Ceara))
    plot(points, pch = 20, add= TRUE)
    

    Output

    enter image description here


    Solution 2 (not recommended)

    Since you seemed to want to do this using the sp and rgdal libraries, here is the code to do the job (this is a solution I don't recommend in the long run, as rgdal will become obsolete in the near future, see here ).

    The problem with your code is that you did not use the right function to read the file: it is necessary to use readOGR() from the rgdal library. Also, I have simplified your code for the selection of Ceara in the sp object estados

    Reprex

    library(rgdal)
    library(sp)
    
    estados <- readOGR("YourPath/lim_unidade_federacao_a.shp") # use readOGR and not readShapePoly
    
    # Select 'Ceara'
    Ceara <- estados[which(estados$sigla == "CE"),] # cleaner code to select 'Ceara'
    
    # Generate the random points in 'Ceara'
    set.seed(452) # set seed for reproducibility
    points <- spsample(Ceara, n = 1000, type = "random")
    
    # Visualization
    plot(Ceara)
    plot(points, pch = 20, add= TRUE)
    

    Created on 2022-01-07 by the reprex package (v2.0.1)