Time to ditch the shapefile!
Here's a reproducible example using a combination of packages sf, gdalUtils and dplyr:
library(sf)
library(dplyr)
library(mapview)
library(gdalUtils)
## as an example we take nc shapefile from package sf
shpfile = system.file("shape/nc.shp", package = "sf")
## set working directory (where to save the converted file)
setwd("test_folder")
## covert to gpkg
target_file = gsub(".shp", ".gpkg", basename(shpfile))
ogr2ogr(src_datasource_name = shpfile,
dst_datasource_name = target_file,
f = "GPKG")
## use dplyr to connect to gpkg file
conn = target_file
db = src_sqlite(conn)
## read fid 10 from gpkg file
pol = tbl(db, "nc") %>%
filter(fid == 10) %>%
collect %>%
st_sf(crs = 4267)
## view with mapview
mapview(pol)
## check with original
mapview(read_sf(shpfile), col.regions = "grey") + pol
This is possible because gpkg
is essentially a self-contained database. Therefore we can read using dplyr database functionality and hence filter by fid
before collect
ing the data into memory. Afterwards we convert to a spatial object (sf
in this case).
sf
package, which at least will grant you a great improvement in reading speed.