提取R中的形状文件对象的质心? [英] Extract centroid of shape file object in R?
问题描述
我有一个形状文件,该文件在以下路径上上传:
I have a shape file, uploaded at the following path:
https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc
我使用"shapefiles"包中的"read.shapefiles"函数导入了数据:
I imported the data using the "read.shapefiles" function in "shapefiles" package:
landuse<- read.shapefile("landuse")
我现在需要提取Landuse对象内所有形状的经/重心并将其添加到landuse $ dbf数据框中
I now need to extract the lat/long centroids of all the shapes within the landuse object and add it to the landuse$dbf dataframe
我尝试了两件事:
lu_df<-coordinates(landuse)
lu_df<-SpatialPoints(landuse)
两个人都给了我以下错误:
Both gave me the following error:
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处理(如投影的输入和输出等).
First, I recommend using the rgdal
package for spatial data. The readOGR
and writeOGR
functions provide nice Shapefile handling (like input and output of projections etc.).
更新:
由于这不适用于@Shaz(请参见注释中的错误),因此使用了maptools
函数readShapePoly()
.另请参见这篇文章.
UPDATE:
Since this is not working for @Shaz (see error in comments), the maptools
function readShapePoly()
was utilized. Also see this post.
问题所在:rgeos
软件包提供了一个函数gCentroid()
,该函数可计算多边形的质心.解决方案看起来像这样:
To your problem: The rgeos
package provides a function gCentroid()
which calculates the centroid of your polygons. The solution looks something like this:
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")
这篇关于提取R中的形状文件对象的质心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!