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

微笑、不失礼 提交于 2019-12-10 03:06:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32571956/get-data-frame-with-polygons-id-and-centroid-lat-long-information-from-shapefi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!