Get data frame with polygons id and Centroid (lat long) information from shapefile

rafa.pereira picture rafa.pereira · Sep 14, 2015 · Viewed 7.5k times · Source

I have a polygon shapefile (downloadable here) from which I want to create a data.frame with 3 columns containing:

  1. Polygon id
  2. Centroid latitude
  3. Centroid Longitude

From this answer here, I know it its quite easy to get this information as a Formal Class SpatialPoints object. And when I convert this object to a data.frame I loose the id information.

# Load Shapefile
  Legislative_areas <- readOGR(dsn = 'C:/Users/.../Downloads/Legislative2010UTM', layer ='Legislative2010UTM')

# Get centroids
  cent <- gCentroid(Legislative_areas, byid=TRUE)

# Convert to data.frame, but loose id info
  cent <- as.data.frame(cent)

Any idea on how to keep the id info?

Answer

hrbrmstr picture hrbrmstr · Sep 14, 2015
library(rgdal)
library(rgeos)

# download w/o wasting bandwidth
URL <- "ftp://dnrftp.dnr.ne.gov/pub/data/state/Legislative2010UTM.zip"
fil <- basename(URL)
if (!file.exists(fil)) download.file(URL, fil)

# unzip & get list of files
fils <- unzip(fil)

# find the shapefile in it
shp <- grep("shp$", fils, value=TRUE)

# get the first layer from it
lay <- ogrListLayers(shp)[1]

# read in the shapefile
leg <- readOGR(shp, lay)

# get the centroids and then convert them to a SpatialPointsDataFrame
leg_centers <- SpatialPointsDataFrame(gCentroid(leg, byid=TRUE), 
                                      leg@data, match.ID=FALSE)

It's just a matter of preserving the @data slot from the original shapefile then making a SpatialPointsDataFrame from the new centroids.

Then you can create a data frame from it or use it in plots or other Spatial… operations directly.