Reputation: 387
I am looking for a method to calculate the center of gravity of each polygon in the list spatialpolygons:
I thought used a loop, but he gets me for the first polygon, I don't know the way, I am new to R, can someone please help me Code:
for ( i in 1:length(polys1_T)) {
xx=mean(coordinates(polys1_T[[i]])[,1])
yy=mean(coordinates(polys1_T[[i]])[,2])
aa<-as.data.frame(cbind(xx,yy))
}
Edit:
Code:
inter1 <- read.table("c:/inter1.csv", header=TRUE)
# add a category (required for later rasterizing/polygonizing)
inter1 <- cbind(inter1,
cat
= rep(1L, nrow(inter1)), stringsAsFactors = FALSE)
# convert to spatial points
coordinates(inter1) <- ~long + lat
# gridify your set of points
gridded(inter1) <- TRUE
# convert to raster
r <- raster(inter1)
# convert raster to polygons
sp <- rasterToPolygons(r, dissolve = T)
plot(sp)
# addition transformation to distinguish well the set of polygons
polys <- slot(sp@polygons[[1]], "Polygons")
# plot
plot(sp, border = "gray", lwd = 2) # polygonize result
inter1.csv result:
Polys is list of 9 polygons :is that it is possible to calculate the center of gravity for each polygon?
Upvotes: 2
Views: 2117
Reputation: 78792
Give rgeos::gCentroid
a look. You can apply it in many ways. If you have a SpatialPolygons object, say, from a call to readOGR
, you can do:
map <- readOGR(dsn, layer)
centers <- data.frame(gCentroid(map, byid=TRUE))
to get all the centroids from it.
As an aside: while accurate—a more common term is "geometric center"/"centroid" vs "center of gravity"
EDIT
For plain, ol Polygon
s (the "hard" way, but slightly more accurate):
library(rgdal)
library(sp)
library(PBSmapping)
library(maptools)
do.call("rbind", lapply(polys, function(x) {
calcCentroid(SpatialPolygons2PolySet(SpatialPolygons(list(Polygons(list(x), ID=1)))))
}))[,3:4]
## X Y
## 1 5.8108434 20.16466
## 2 -3.2619048 29.38095
## 3 5.5600000 34.72000
## 4 3.8000000 32.57037
## 5 6.3608108 32.49189
## 6 -2.2500000 31.60000
## 7 -8.1733333 27.61333
## 8 0.3082011 27.44444
## 9 8.6685714 26.78286
and, to use your nearly-equivalent by-hand-method:
do.call("rbind", lapply(polys, function(x) {
data.frame(mean(coordinates(x)[,1]), mean(coordinates(x)[,2]))
}))
## mean.coordinates.x....1.. mean.coordinates.x....2..
## 1 5.819892 20.15484
## 2 -3.242593 29.37778
## 3 5.539474 34.71579
## 4 3.815517 32.56552
## 5 6.323034 32.47191
## 6 -2.230952 31.60000
## 7 -8.140476 27.61905
## 8 0.350000 27.40885
## 9 8.746825 26.92063
Each method gives you the centroid for each list element (and there are 9—not 5—in the example you provided).
If you ever have a huge list of these, consider using rbindlist
from the data.table
package (speedier + more memory efficient).
Upvotes: 5