简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM