Extract centroid of shape file object in R?

2019-07-13 21:53发布

问题:

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