# [R-sig-Geo] Population-weighted Centroids of Polygons in R

Loïc Dutrieux loic.dutrieux at wur.nl
Sun Feb 21 23:44:28 CET 2016

```Hi Sohrab,

I don't think there is a method for weighted centroids specifically.
What if you get the centroid coordinates of each "block" using
gCentroid() and calculate a weighted average of the coordinates of every
centroid?
See an example below assuming your blocks are a
SpatialPolygonsDataFrame. It's quite a simple approach; not sure how
valid it would be with more complex features though (eg: with holes, etc)...

Cheers,
Loïc

library(rgeos)
library(sp)

# Generate SpatialPolygonsDataFrame object (blocks with population data)
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
sp <- spPolygons(cds1, cds2)
spdf <- SpatialPolygonsDataFrame(sp, data.frame(pop = c(25,32)))

# Get centroid of every polygon
centroids <- gCentroid(spdf, byid = TRUE)

# Get a dataframe with coordinates of centroids and weights
df <- cbind(data.frame(centroids), spdf at data)

# SpatialPoints corresponding to Weighted centroid
SpatialPoints(data.frame(x = weighted.mean(df\$x, df\$pop), y =
weighted.mean(df\$y, df\$pop)))

On 02/21/2016 09:10 PM, Sohrab Abbasnejad via R-sig-Geo wrote:
> Dear all,
> I have a set of spatial polygons and several blocks of population (with fixed area but a different number of people in each). I have used the "over" method from "sp" package to identify the blocks which are located inside these polygons.
> Now, utilizing R, I wish to assign to each of these polygons a centroid in terms of the population using some kind of distance (Euclidean/shortest path, etc.). In fact, I am looking for the exact coordinates of a population-weighted centroid for each of my polygons.
> Any ideas would be welcome. I truly appreciate your time.
> Sincerely,Sohrab
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

```