I've spent a little while figuring out the answer to this question. It's not immediately obvious from a Google search, so thought it may useful to post the answer on here. There is also an additional question about non-contiguous polygons.
Instant easy answer: use the command:
centroids <- getSpPPolygonsLabptSlots(polys)
(This was found in the class description of the SpatialPolygonsDataFrame R data class for the overarching spatial package in R, sp)
This seems to do exactly the same thing as
cents <- SpatialPointsDataFrame(coords=cents, data=sids@data, proj4string=CRS("+proj=longlat +ellps=clrk66"))
in the following code, which should be replicable on any R installation (try it!)
#Rcentroids
install.packages("GISTools")
library(GISTools)
sids <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1],
proj4string=CRS("+proj=longlat +ellps=clrk66"))
class(sids)
plot(sids)
writeSpatialShape(sids, "sids")
cents <- coordinates(sids)
cents <- SpatialPointsDataFrame(coords=cents, data=sids@data,
proj4string=CRS("+proj=longlat +ellps=clrk66"))
points(cents, col = "Blue")
writeSpatialShape(cents, "cents")
centroids <- getSpPPolygonsLabptSlots(sids)
points(centroids, pch = 3, col = "Red")
Where cents (blue) and centroids (red) are identical centroids (this should plot should appear after you've run the code):
So far so good. But when you calculate polygon centroids in QGIS (menu: Vector | Geometry | Polygon Centroids ), there are slightly different results for non-contiguous polygons:
So this question is 3-things:
- A quick and easy answer
- A warning for people using R to calculate centroids for non-contiguous polygons
- A question about how it should be done in R to properly account for multi-part (non-contiguous) polygons