I have a road shapefile from the following location
https://www.globio.info/download-grip-dataset
I downloaded the shapefile for North America and subset the roads for Canada as follows:
library(raster)
library(ggplot2)
library(sf)
library(sp)
road <- read_sf(file.path(dir_ls$base,"roadshapefile","GRIP4_Region1_vector_shp","GRIP4_region1.shp"))
road_canada <- road %>%
dplyr::filter(GP_RTP %in% c(1,2), # 1 for highways
GP_REX == 1, # 1 for Open
GP_RRG == 1, # 1 is for Canada
GP_RCY == 124 # for Canada
)
ggplot(road_canada) + geom_sf()
I want to generate 20 random latlon along the roads
spsample(road_canada, n=20, type="random")
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘spsample’ for signature ‘"sf"’
I understand the error that beacause of sf class, this method is not working. I am not aware of any other method that will enable me to do it and wondered if anyone knows any alternative?
Using st_sample
works, but wasn't totally straightforward. The size of the road data makes it hard to work with in-memory.
Below the road_canada
object is simplified, uses only the geometry column, combined, sampled, and finally had to be cast to POINT
to get the coordinates to show up.
# Use only the geometry column, simplify for a smaller object.
road_canada <- st_geometry(road_canada) %>% rmapshaper::ms_simplify()
road_sample <- road_canada %>%
st_combine() %>%
st_sample(20) %>% ## Returns MULTIPOINT EMPTY, fixed with st_cast('POINT')
st_cast('POINT')
head(road_sample)
#Geometry set for 6 features
#Geometry type: POINT
#Dimension: XY
#Bounding box: xmin: -117.3209 ymin: 52.32145 xmax: -109.5217 ymax: 58.59094
#Geodetic CRS: WGS 84
#First 5 geometries:
#POINT (-109.5217 52.4055)
#POINT (-117.3209 52.32145)
#POINT (-112.3959 53.01749)
#POINT (-112.9708 53.5703)
#POINT (-113.9 54.38767)