Search code examples
rgisrgdal

converting from coordinate data to latitude and longitude in R?


I have been using the following code to read in census tract data and produce centroid data for each census tract. I would like to pull latitude and longitude from this for some sampling I am doing through the Foursqaure API which requires latitude and longitude. I notice that this code gives me back the coordinate system different from latitude longitude. Any idea how I might be able to extract latitude longitude whether is be converting the coordinates or through a different function?

#load libraries-----------------------------
library(rgdal)
library(sp)
library(GISTools)
library(ggplot2)

#load census tact file------------------------
tracts = readOGR("nycb2010.shp", layer="nycb2010")

#extract centroids
centroids = as.data.frame(getSpPPolygonsLabptSlots(tracts))

#map new data
ggplot() +  geom_polygon(data=tracts, aes(x=long, y=lat, group=group), fill="black", colour="grey90", alpha = 1)+
  geom_point(data=centroids, aes(x=V1, y=V2, group = 1, color = 'red'), size = .1)

Solution

  • You can use the function spTransform to change the coordinate system of your spatial data, like this :

    library(sp)
    library(rgdal)
    
    lat_long = CRS("+init=epsg:4326") 
    tracts_lat_long <- spTransform(tracts, lat_long)
    
    proj4string(tracts_lat_long)
    [1] "+init=epsg:3035 +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"