本文介绍了从 shapefile 中获取具有多边形 id 和质心(经纬度)信息的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多边形 shapefile(可从 这里下载)我想创建一个包含 3 列的 data.frame:

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

  1. 多边形 ID
  2. 质心纬度
  3. 质心经度

从这个答案这里,我知道很容易得到此信息作为 Formal Class SpatialPoints 对象.当我将此对象转换为 data.frame 时,我丢失了 id 信息.

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)

知道如何保留 ID 信息吗?

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)

这只是保留原始 shapefile 中的 @data 槽然后从新质心制作 SpatialPointsDataFrame 的问题.

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.

这篇关于从 shapefile 中获取具有多边形 id 和质心(经纬度)信息的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 02:18