1

I have a county shapefile and a DEM raster, I want to extract mean DEM of every counties. There is a function 'zonal' in raster package, however, it requires raster not shapefile.

enter image description here How can I do this in R?

1

2 Answers 2

6

As recommended raster::extract will accomplish what you are after. However, from a computational speed and modernization standpoint, I would recommend using the terra package, which is a replacement for raster. The terra::extract function is almost identical to the raster version but, written in Rcpp and notably faster. Whereas the syntax is the same as raster::extract, the terra version requires coercing your polygon vector data to a terra Vect class, which can be done in the function eg., terra::extract(raster, vect(polys), 'mean'). The polygons can be an sf or sp class.

Another alternative is exact_extract function in the exactextractr package, which allows for a weighted overlay (eg., mean, sum) based on the fractional intersection of cells with the polygons. The polygons need to be an sf class object but the raster(s) can be raster or terra objects. You can read in your polygons using sf::st_read.

0
0

Use the extract function from the raster package:

Description:

     Extract values from a Raster* object at the locations of spatial
     vector data. There are methods for points, lines, and polygons
     (classes from `sp` or `sf`), for a matrix or data.frame of points.
     You can also use cell numbers and Extent (rectangle) objects to
     extract values.

The first parameter is a raster, the second can be spatial polygons read in from a shapefile using readOGR or similar. Read the help for more complete info.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.