如何简化 R 中的角度(以度为单位)?

how to simplify angles (in degrees) in R?

我正在构建一个手动/手动/判断因子轮换函数。

显然,旋转二维坐标系270°-90°相同,720°相同。

我想简化用户输入,使所有值都在 -180°180° 之间。

如何在 R 中优雅地做到这一点?

Ps.: 还是存储从 360° 的值更有意义? 用户可能希望顺时针和逆时针旋转,所以我认为 -180180 从用户体验的角度来看可能更直观。

类似的东西?

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

你只想让所有数字都是它们的余数 mod 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

编辑:

如果你想让数字在-180到180之间,最后去掉180就可以了。

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

现在

  • 0 -> -180

  • 360 -> 180。

根据@Pascal 的回答,这里有一个稍微扩展的版本(笨拙地?)将角度转换为 -180°180° 的范围(出于用户体验原因):

  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)

}

这产生:

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