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

时间:2016-04-17 06:56:17

标签: r geospatial shapefile centroid

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

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

我使用" read.shapefiles"导入了数据。功能" shapefiles"包:

landuse<- read.shapefile("landuse")

我现在需要提取landuse对象中所有形状的纬度/长度质心并将其添加到landuse $ dbf dataframe

我尝试了两件事:

lu_df<-coordinates(landuse)
lu_df<-SpatialPoints(landuse)

两者都给了我以下错误:

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

我不确定如何继续。

1 个答案:

答案 0 :(得分:2)

首先,我建议将rgdal包用于空间数据。 readOGRwriteOGR函数提供了良好的Shapefile处理(如投影的输入和输出等)。

<强>更新: 由于这不适用于@Shaz(请参阅注释中的错误),因此使用了maptools函数readShapePoly()。另请参阅this post

解决您的问题: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")