18

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
  • 4,656
  • 1
  • 27
  • 49
  • 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

2 Answers2

13

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
  • 4,484
  • 3
  • 26
  • 49
  • Can you print sf version, this yields Error in methods::validObject(y) : invalid class “Extent” object: TRUE, same raster version. – bw4sz Aug 21 '18 at 17:38
  • Sure @bw4sz, `packageVersion("sf")` is `‘0.6.4’`. – fdetsch Aug 22 '18 at 05:51
  • I'm still getting this error with sf `0.7.1` and raster `2.7.15` on OS X (Mojave). Did this get un-fixed? – pbaylis Oct 31 '18 at 01:17
2

The announce of "sf" package available on CRAN was written on January 2017.
The last release of "raster" package was in June 2016.

"sf" package is too new to yet work with raster package.
So, for now, you need to use your "ugly workarounds"...

Sébastien Rochette
  • 5,901
  • 2
  • 14
  • 39