Get data frame with identifiers of polygons and Centroid (lat long) from shapefile

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

  • Polygon ID
  • latitude centroid
  • Center life

From this answer here , I know that it is quite easy to get this information as a Formal Class SpatialPoints . And when I convert this object to a data.frame file, I lose the identifier 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 save the credentials?

+6
source share
1 answer
 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 is just a matter of saving the @data slot from the original form file and then creating the SpatialPointsDataFrame from the new centroids.

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

+9
source

All Articles