Extract centroid of shape file object in R?

自闭症网瘾萝莉.ら 提交于 2019-12-13 16:44:17

问题


I have a shape file, uploaded at the following path:

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

I imported the data using the "read.shapefiles" function in "shapefiles" package:

landuse<- read.shapefile("landuse")

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

I tried two things:

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

I am not sure on how to proceed.


回答1:


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.).

UPDATE: Since this is not working for @Shaz (see error in comments), the maptoolsfunction readShapePoly()was utilized. Also see this post.

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")


来源:https://stackoverflow.com/questions/36673576/extract-centroid-of-shape-file-object-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!