TransWikia.com

Finding centroid of cluster of points using R

Geographic Information Systems Asked by Roman Luštrik on August 15, 2021

While searching the web, solutions for finding centroids of polygons come up rather often. What I’m interested in is finding a centroid of a cluster of points. A weighted mean of sorts.

Can you provide some pointers, pseudo code (or even better, an R package that has already solved this) or links of how this issue can be tackled?


@iant has suggested a method to average coordinates and use that for the centroid. This is exactly what crossed my mind when I saw the right picture on this web page.

Here is some simple R code to draw the following figure that demonstrates this (× is the centroid):

xcor <- rchisq(10, 3, 2)
ycor <- runif(10, min = 1, max = 100)
mx <- mean(xcor)
my <- mean(ycor)

plot(xcor, ycor, pch = 1)
points(mx, my, pch = 3)

enter image description here


cluster::pam()$medoids returns a medoid of a set of cluster. This is an example from @Joris Meys:

library(cluster)
df <- data.frame(X = rnorm(100, 0), Y = rpois(100, 2))
plot(df$X, df$Y)
points(pam(df, 1)$medoids, pch = 16, col = "red")

3 Answers

just average the X and Y coordinates (multiply by a weight if you want) and there is your centroid.

Correct answer by Ian Turton on August 15, 2021

You can use the centroid function from geosphere package.

https://www.rdocumentation.org/packages/geosphere/versions/1.5-5/topics/centroid

Answered by Leonardo Leite Ferraz de Campo on August 15, 2021

This is excellent. I'd suggest removing outliers before doing this. For simple outlier removal, one might find the longitudes within the 75%-25% percentiles and the same for the latitudes, and only calculate mean on those values? Or for less drastic outlier removal, remove values outside the 1.5 * 75%-25% interquartile range (this is a somewhat standard outlier definition).

Answered by Christer P. Volk on August 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP