Crop simple features object in R
Since today, there is a st_crop
function in the github version of sf
(devtools::install_github("r-spatial/sf")
, probably on CRAN in the near future too).
Just issue:
st_crop(nc, c(xmin=-82, xmax=-80, ymin=35, ymax=36))
The vector must be named with xmin xmax ymin ymax
(in whichever order).
You can also use any object that can be read by st_bbox
as cropping limits, which is very handy.
st_intersection
is probably the best way. Find whatever way works best to get an sf
object to intersect with your input. Here's a way using the convenience of raster::extent
and a mix of old and new. nc
is created by example(st_read)
:
st_intersection(nc, st_set_crs(st_as_sf(as(raster::extent(-82, -80, 35, 36), "SpatialPolygons")), st_crs(nc)))
I don't think you can coax st_intersection
to not need an exact matching CRS, so either set both of them to NA or make sure they are the same. There's no easy tools for bbox/extent afaik, so using raster is good way to make things easy-ish.
Another workaround, for me it was faster for larger shapefiles:
library(sf)
library(raster)
library(rgeos)
library(ggplot2)
# Load National Forest shapefile
# https://data.fs.usda.gov/geodata/edw/edw_resources/shp/S_USA.AdministrativeForest.zip
nf.poly <- st_read("S_USA.AdministrativeForest"), "S_USA.AdministrativeForest")
crop_custom <- function(poly.sf) {
poly.sp <- as(poly.sf, "Spatial")
poly.sp.crop <- crop(poly.sp, extent(c(-82, -80, 35, 36)))
st_as_sf(poly.sp.crop)
}
cropped <- crop_custom(nf.poly)