[Math] “How to sort vertices of a polygon in counter clockwise order?”: Computing Angle

geometrypolygonsvectors

my question relates to the answer to the following question:
How to sort vertices of a polygon in counter clockwise order?

I don't have a strong background in linear algebra… I don't understand this statement:

Then you can compute the angle of each vertex to the center point, and sort according to the computed angle

Is this a polar angle? What function could I use in R to compute this?

Best Answer

The function $\operatorname{atan2}$ is defined in R so just use it. This is indeed a polar angle, with a few subtleties.

Choose a "central point" $(\hat x, \hat y)$, and for each point $(x,y)$ calculate its angle as $\operatorname{atan2}(x-\hat x,y-\hat y)$. Sort the points using those angles as keys, and there is your polygon.

Note that if the polygon is not convex you may get a different answer if you choose a different "central point". Also make sure the point really is "inside" the polygon. Choosing the average values of $x$ and of $y$ should work well enough.