Thursday, 5 April 2018

r - find the centroid of a cluster of points


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. I would appreciate it if someone could 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.


EDIT


Convergence has been afoot (again). 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



EDIT 2


cluster::pam()$medoids returns a medoid of a set of cluster. This is an example shamelessly stolen 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")

Answer



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...