Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

shape

spatial

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?

like image 600
rafa.pereira Avatar asked Sep 14 '15 18:09

rafa.pereira


1 Answers

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.

like image 112
hrbrmstr Avatar answered Sep 30 '22 08:09

hrbrmstr