How to simplify angles (in degrees) in R?

I build a manual / manual / conditional factor rotation function.

Obviously, the rotation of the two-dimensional coordinate system 270°coincides with -90°, and 720°coincides with .

I would like to simplify user input so that all values ​​are between -180°and 180°.

How can I make it elegant in R?

Ps .: Or would it be wiser to store values ​​from to 360°? Users may also want to turn the clock counterclockwise, so I think that -180up 180can be more intuitive from a UX point of view.

+4
source share
3 answers

Sort of?

x <- 90 + c(0,360,720)
x
# [1]  90 450 810

(x*pi/360) %% pi
# in radians:
#[1] 0.7853982 0.7853982 0.7853982

# in degrees
((x*pi/360) %% pi)*360/pi
#[1] 90 90 90
+5
source

, 360?

, 0 360.

to_degrees <- function(x) x %% 360 
to_degrees(720)
[1] 0
to_degrees(-90)
[1] 270
to_degrees(300 + 100)
[1] 40

EDIT:

, -180 180, 180 .

to_degrees <- function(x) x %% 360 -180

  • 0 → -180

  • 360 → 180.

+3

based on @Pascal's answer, here is a slightly extended version that (clumsy?) converts angles to a range from -180°to 180°(for UX reasons):

  simplify.angle <- function (angle.raw) {  # simplify angles to -180° to 180°
  angle.360 <- ((angle.raw*pi/360) %% pi)*360/pi
  if (angle.360 > 180) {
    angle.simple <- angle.360 - 360
  } else if (angle.360 < -180) {
    angle.simple <- angle.360 + 360
  } else {
    angle.simple <- angle.360
  }
  return(angle.simple)

}

This gives:

> sapply(c(-90, 270, 630, -450, -181), simplify.angle)
[1] -90 -90 -90 -90 179
+1
source

All Articles