I need to use the function extract() to do a weighted average extraction from a raster using a grid cell of equal sized squares. My polygon grid is in UTM21n and the raster is in GCS WGS84 datum D. Do I have to reproject the raster before using it into extract()? Or will the function handle it properly?
Asked
Active
Viewed 960 times
2 Answers
5
You can find the source code of function extract
for SpatialPolygons
here. The code starts with the following snippet:
setMethod('extract', signature(x='Raster', y='SpatialPolygons'),
function(x, y, fun=NULL, na.rm=FALSE, weights=FALSE, cellnumbers=FALSE, small=FALSE, df=FALSE, layer, nl, factors=FALSE, sp=FALSE, ...){
px <- projection(x, asText=FALSE)
comp <- .compareCRS(px, projection(y), unknown=TRUE)
if (!comp) {
.requireRgdal()
warning('Transforming SpatialPolygons to the CRS of the Raster')
y <- spTransform(y, px)
}
...
Which suggests that extract
does in fact perform the projection itself (changing the projection of the SpatialPolygon to the projection of the raster), despite the fact that it is not documented in the help page.

plannapus
- 18,529
- 4
- 72
- 94
-
+1 Annoyingly I wrote a wrapper function around extract to handle this exact situation because this functionality is undocumented. Good to know, thanks! – Simon O'Hanlon Oct 11 '13 at 08:30
-
Interesting, I wonder what happens if the projection is not set in the polygon layer. – Herman Toothrot Oct 11 '13 at 15:21
0
The documentation does not mention automatic reprojection. So, I think it is save to assume the function does not do this. Therefore, you need to reproject yourself before calling extract
.

Paul Hiemstra
- 59,984
- 12
- 142
- 149