在 R 中提取形状文件对象的质心?
Extract centroid of shape file object in R?
我有一个形状文件,上传到以下路径:
https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc
我使用 "shapefiles" 包中的 "read.shapefiles" 函数导入了数据:
landuse<- read.shapefile("landuse")
我现在需要提取 landuse 对象中所有形状的 lat/long 质心并将其添加到 landuse$dbf 数据框
我尝试了两件事:
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
我不确定如何进行。
首先,我建议使用 rgdal
空间数据包。 readOGR
和 writeOGR
函数提供了很好的 Shapefile 处理(如投影的输入和输出等)。
更新:
由于这不适用于 @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")
我有一个形状文件,上传到以下路径:
https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc
我使用 "shapefiles" 包中的 "read.shapefiles" 函数导入了数据:
landuse<- read.shapefile("landuse")
我现在需要提取 landuse 对象中所有形状的 lat/long 质心并将其添加到 landuse$dbf 数据框
我尝试了两件事:
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
我不确定如何进行。
首先,我建议使用 rgdal
空间数据包。 readOGR
和 writeOGR
函数提供了很好的 Shapefile 处理(如投影的输入和输出等)。
更新:
由于这不适用于 @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")