R Tutorial R Charts & Graphs R Statistics R References

R - atan2() Function



The R atan2() function returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). The returned value will be in the range -𝜋 through 𝜋. In special cases it returns the following:

  • If either argument is NaN, then the result is NaN.
  • If both arguments are positive infinity, then the result is closest to 𝜋/4.
  • If the first argument is positive or negative finite and the second argument is positive infinity, then the result is zero.
  • If the first argument is positive or negative finite and the second argument is negative infinity, then the result is closest to 𝜋.
  • If the first argument is positive and the second argument is zero, or the first argument is positive infinity and the second argument is finite, then the result is closest to 𝜋/2.
  • If the first argument is negative and the second argument is zero, or the first argument is negative infinity and the second argument is finite, then the result is closest to -𝜋/2.
  • If the first argument is positive infinity and the second argument is negative infinity, then the result is closest to 3*𝜋/4.
  • If the first argument is negative infinity and the second argument is positive infinity, then the result is closest to -𝜋/4.
  • If both arguments are negative infinity, then the result is closest to -3*𝜋/4.

Syntax

atan2(y, x)

Parameters

y Required. Specify column of ordinate coordinate to compute on.
x Required. Specify column of abscissa coordinate to compute on.

Return Value

Returns theta of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

Example:

In the example below, atan2() function is used to calculate the theta of a point.

#operating on single element atomic vectors
print(atan2(10, 10))
print(atan2(0, 10))
print(atan2(-10, 10))
print(atan2(-10, -10))

cat("\nOperating on vectors\n")
#operating on vectors
v1 <- c(0, 10, Inf)
v2 <- c(10, 20, -Inf)
print(atan2(v1, v2))

cat("\nOperating on matrices\n")
#operating on matrices
m1 <- matrix(c(-2, Inf, 10, -10, Inf, NaN), nrow=2)
m2 <- matrix(c(2, NaN, 20, 20, 0, NaN), nrow=2)
print(atan2(m1, m2))

cat("\nOperating on first column of matrices\n")
#operating on first column of matrices
print(atan2(m1[,1], m2[,1]))

The output of the above code will be:

[1] 0.7853982
[1] 0
[1] -0.7853982
[1] -2.356194

Operating on vectors
[1] 0.0000000 0.4636476 2.3561945

Operating on matrices
           [,1]       [,2]     [,3]
[1,] -0.7853982  0.4636476 1.570796
[2,]        NaN -0.4636476      NaN

Operating on first column of matrices
[1] -0.7853982        NaN

❮ R Math Functions