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.
This exercise is part of the course
Visualizing Geospatial Data in R
Exercise instructions
- Transform
neighborhoods
to have the same CRS asnyc_tracts
by usingspTransform()
with theCRS
argument 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_tracts
withadd = TRUE
andcol = "red"
, and finally plottingwater
withadd = TRUE
andcol = "blue"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(sp)
library(raster)
# Use spTransform on neighborhoods: neighborhoods
# head() on coordinates() of neighborhoods
# Plot neighborhoods, nyc_tracts and water