【问题标题】:Get data frame with polygons id and Centroid (lat long) information from shapefile从 shapefile 获取具有多边形 id 和质心(纬度)信息的数据框
【发布时间】:2015-09-14 18:58:07
【问题描述】:

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

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

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

# 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 信息吗?

【问题讨论】:

    标签: r shape spatial


    【解决方案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)
    

    只需从原始 shapefile 中保留 @data 插槽,然后从新质心创建 SpatialPointsDataFrame

    然后您可以从中创建一个数据框,或者直接在绘图或其他Spatial… 操作中使用它。

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 2013-01-16
      • 2018-01-25
      • 2021-10-19
      • 1970-01-01
      • 2013-11-29
      • 2021-09-09
      • 2013-11-22
      • 2019-02-04
      相关资源
      最近更新 更多