在R中提取形状文件对象的质心?

Sha*_*haz 3 r geospatial shapefile centroid

我有一个形状文件,上传到以下路径:

https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc

我使用“shapefiles”包中的“read.shapefiles”函数导入了数据:

landuse<- read.shapefile("landuse")
Run Code Online (Sandbox Code Playgroud)

我现在需要提取 landuse 对象内所有形状的纬度/经度质心并将其添加到 landuse$dbf 数据帧

我尝试了两件事:

lu_df<-coordinates(landuse)
lu_df<-SpatialPoints(landuse)
Run Code Online (Sandbox Code Playgroud)

两者都给了我以下错误:

Error in coordinates(as.data.frame(obj)) : 
  error in evaluating the argument 'obj' in selecting a method for function 'coordinates': Error in data.frame(record = 1L, content.length = 80L, shape.type = 5L,  : 
  arguments imply differing number of rows: 1, 4, 7
Run Code Online (Sandbox Code Playgroud)

我不确定如何进行。

lok*_*oki 5

首先,我建议使用rgdal空间数据包。的readOGRwriteOGR功能提供好的Shape文件处理(如输入和预测的输出等)。

更新:由于这不适用于@Shaz(请参阅评论中的错误),因此使用了该maptools功能readShapePoly()。另请参阅此帖子

对于您的问题:该rgeos包提供了一个gCentroid()计算多边形质心的函数。解决方案如下所示:

setwd("/path/to/your/shapefile/")

library(maptools)
library(rgeos)
landuse <- readShapePoly("landuse") 

centr <- gCentroid(landuse, byid = TRUE)

# create SpatialPointsDataFrame to export via writeOGR
# positive side effect: All data from landuse@data joined to centr@data
centr <- SpatialPointsDataFrame(centr, data= landuse@data) 

writeOGR(centr, ".", "landuse_centroids", driver = "ESRI Shapefile")
Run Code Online (Sandbox Code Playgroud)