Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert cartesian angles to polar / compass / cardinal angles in R?

This is a problem that I fought with for a bit and couldn't find a good answer out there. I did eventually solve it in R, but thought I would post it anyway in case others need it. If anyone has a more elegant solution, I would love to see it. This is a bit of a brute force effort.

I have a series of paired XY (Cartesian) coordinates. I can easily get the angles between them using a simple atan() command. However, I want the angles in compass (polar? cardinal?) directions (where north=0°, east=90°, and so forth). Here's a minimal example to make the data and the Cartesian angles, and I've posted my brute force conversion to compass angle below. The degree conversion (from radians) uses deg() from the 'circular' package.

require(circular)
test <- data.frame(x=c(0,1,1,1,0,-1,-1,-1),y=c(1,1,0,-1,-1,-1,0,1))
test$angle <- deg(atan(test$y/test$x))
test

...produces

   x  y angle
1  0  1    90
2  1  1    45
3  1  0     0
4  1 -1   -45
5  0 -1   -90
6 -1 -1    45
7 -1  0     0
8 -1  1   -45

Note that the angles into the lower-left and upper-left quadrants are the same as that into the lower- and upper-right quadrants, losing the directionality of the vectors.

like image 933
David Roberts Avatar asked Jan 22 '26 00:01

David Roberts


1 Answers

ang <- function(x,y) { 
  z <- x + 1i * y
  res <- 90 - Arg(z) / pi * 180
  res %% 360
}

ang(test$x, test$y)
#[1]   0  45  90 135 180 225 270 315
like image 144
Roland Avatar answered Jan 24 '26 13:01

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!