Converting from one CRS/projection to another
The process of converting from one CRS or projection to another is handled by the spTransform() methods in the rgdal package. spTransform() has methods for all sp objects including SpatialPolygonsDataFrame, but doesn't work on raster objects. This is because transforming a raster is a little more complicated; the transformed rectangular grid will no longer be rectangular. You can look at ?raster::projectRaster if you are curious about transforming rasters.
Transformation is simple. The first argument to spTransform(), x, is the spatial object to be transformed and the second, CRS, is a specification of the desired CRS. The CRS can be specified by a PROJ4 string, which you could construct by hand, but it's much easier to take it from an existing object (e.g. with the proj4string() function).
Time to get your two polygons datasets into the same CRS.
Cet exercice fait partie du cours
Visualizing Geospatial Data in R
Instructions
- Transform
neighborhoodsto have the same CRS asnyc_tractsby usingspTransform()with theCRSargument set toproj4string(nyc_tracts). - Verify the transformation by looking at the
head()ofcoordinates(neighborhoods). - Check the datasets now line up by plotting
neighborhoods, then plottingnyc_tractswithadd = TRUEandcol = "red", and finally plottingwaterwithadd = TRUEandcol = "blue".
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
library(sp)
library(raster)
# Use spTransform on neighborhoods: neighborhoods
# head() on coordinates() of neighborhoods
# Plot neighborhoods, nyc_tracts and water