Previously I was using raster::crop
and raster::mask
with shapefiles of class Spatial*, read in using rgal::readOGR
.
I am just "upgrading" my scripts to use sf
for reading and manipulating polygons.
raster::crop
expects an 'extent' object as second argument. Up to now, this was automatically extracted from a Spatial* object. So I could just do raster::crop(raster, polygon)
.
To get this working with an sf
object, I can call raster::crop(raster, as.vector(st_bbox(polygon)))
as an ugly workaround.
Since raster::mask
clearly expects a Raster* object or a Spatial* object
the only solution was to coerce the sf
object back to a Spatial* object using as("Spatial")
.
I assume this problem generalized to all raster
functions? Did I overlook something or is it just the case that the raster
package does not (yet) work with sf
objects?
sf: Simple Features for R Support for simple features, a standardized way to encode spatial vector data. Binds to 'GDAL' for reading and writing data, to 'GEOS' for geometrical operations, and to 'PROJ' for projection conversions and datum transformations.
Geometries are the basic building blocks of simple features. Simple features in R can take on one of the 17 geometry types supported by the sf package. In this chapter we will focus on the seven most commonly used types: POINT , LINESTRING , POLYGON , MULTIPOINT , MULTILINESTRING , MULTIPOLYGON and GEOMETRYCOLLECTION .
The SF (or Simple Features) library is a big change in how R handles spatial data. Back in the 'old days', we used a package called SP to manage spatial data in R. It was initially developed in 2005, and was a very well-developed package that supported practically all GIS analysis.
For future reference, it works now! Here's some slightly modified example code from ?crop
, tested with raster version 2.6-7 which has been released on 2017-11-13.
library(raster)
library(sf)
r <- raster(nrow=45, ncol=90)
r[] <- 1:ncell(r)
# crop Raster* with sf object
b <- as(extent(0, 8, 42, 50), 'SpatialPolygons')
crs(b) <- crs(r)
b <- st_as_sf(b) # convert polygons to 'sf' object
rb <- crop(r, b)
# mask Raster* with sf object
mb <- mask(r, b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With