Reputation: 183
I found that using
angle <- (acos(sum(a*b) / (sqrt(sum(a * a)) * sqrt(sum(b * b)))))
is the most common way to get an angle between two vectors a
and b
in R.
Unfortunately, I keep on getting errors on certain vectors that seem to lay on each other or have an angle of about 180 degrees between each other.
For example:
a <- c(-7.6942088429381328e-01, 2.4999999999999989e-01)
b <- c(-5.4146791834239578e+08, 1.7593359143824694e+08)
do not work.
I am facing similar problems with other ways of calculating an angle.
Upvotes: 2
Views: 109
Reputation: 50718
I would use vector operations.
Let's define a proper function angle
that takes as arguments two vectors x1
and x2
angle <- function(x1, x2, tol = 1e-6) {
cost <- as.numeric((x1 %*% x2) / (sqrt(x1 %*% x1) * sqrt(x2 %*% x2)))
if (abs(cost - 1) < tol) return(0) else return(acos(cost))
}
Note that we do a numeric stability check to ensure that for angles close to 0, we get a numeric result (instead of NA
).
Then to calculate the angle (in radians) between two vectors, e.g.
x1 <- c(1, 1)
x2 <- c(0.5, 2)
we do
angle(x1, x2)
#[1] 0.5404195
In your case,
angle(a, b)
#[1] 0
Note that this will also work for higher dimensional vectors, e.g.
x1 <- c(1, 1, 1)
x2 <- c(0.5, 2, 0)
angle(x1, x2)
#[1] 0.7952027
Upvotes: 2