19

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

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.

raster::mask

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?

pat-s
  • 5,992
  • 1
  • 32
  • 60
  • 2
    You don't want `as.vector(st_bbox(pnt_buf))` but rather `as.vector(st_bbox(pnt_buf))[c(1, 3, 2, 4)]`, because crop expects `c(xmin, xmax, ymin, ymax)` – jsta Jul 15 '17 at 21:12

1 Answers1

15

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)
fdetsch
  • 5,239
  • 3
  • 30
  • 58