Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Handling of sf objects in raster package

Tags:

r

r-raster

sf

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?

like image 261
pat-s Avatar asked Mar 21 '17 12:03

pat-s


People also ask

What does the SF package in R do?

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.

What are the main types of geographical simple feature objects available in the R sf package?

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 .

What is the difference between SF and SP in R?

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.


1 Answers

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)
like image 146
fdetsch Avatar answered Nov 15 '22 20:11

fdetsch