Raster in R – Synchronizing RasterStack and SpatialPolygonsDataFrame to the Same Coordinate System

rrasterrgdal

I have a shapefile of 8094 Italian municipalities which I imported into R as a SpatialPolygonsDataFrame using readOGR. When I plot this, I get the following map:

enter image description here

I also have a RasterStack of global monthly temperatures.

I want to overlay the rasterstack with the shapefile to extract the values for each municipality. I have done this many times before (with other shapefiles) using the extract command in R, i.e., monthly_temperatures <- raster::extract(tmp_month, Italy_map)

However, this time it doesn't work because the RasterStack and the SpatialPolygonsDataFrame use different coordinate systems. The proj4string of the Italy map is +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs and the bbox is as follows:

    min     max
x  313279.3 1312016
y 3933520.1 5220291

Of the RasterStack the proj4string is +proj=longlat +datum=WGS84 +no_defs and the bbox is as follows:

    min     max
x  -180    180
y   -90     90

They clearly do not overlap. Does someone know how to fix this issue? I have looked for different shapefiles of Italian municipalities online but the one from ISTAT is the only one I have found. I am working in RStudio.

Best Answer

As far I know, R doesn't project on the fly while processing with multiple layers. All layers should share CRS for any process.

For projecting CRS, use spTransform. Always project the vector file over the raster file:

Italy_mapWGS84 <- spTransform(Italy_map, CRS('+proj=longlat +datum=WGS84 +no_defs'))

monthly_temperatures <- raster::extract(tmp_month, Italy_mapWGS84)