What the most efficient way in the programming language R to calculate the angle between two vectors?
I think what you need is an inner product. For two vectors v,u
(in R^n
or any other inner-product spaces) <v,u>/|v||u|= cos(alpha)
. (were alpha
is the angle between the vectors)
for more details see:
You should use the dot product. Say you have V1 = (x1, y1, z1) and V2 = (x2, y2, z2): then
the dot product, which I'll denote by V1*V2, is calculated as
V1*V2 = X1*X2 + Y1*Y2 + Z1*Z2 = |V1|*|V2|*cos(theta);
(I'm using an "*" where mathematical notation would normally use an actual period, because there is no way to elevate a period to the center of the text line.)
What this means is that that sum shown on the left is equal to the product of the absolute values of the vectors times the cosine of the angle between the vectors. the absolute value of the vector V1 is calculated as
|V1| = SquareRoot(x1^2 + y1^2 + z1^2), (I'm using "^2" to indicate squaring)
and analogously for |V2|, of course.
So, if you rearrange the first equation above, you get
cos(theta) = (x1*x2 + y1*y2 + z1*z2)/(|V1|*|V2|),
and you just need the arccos function (or inverse cosine) applied to cos(theta) to get the angle.
Depending on your arccos function, the angle may be in degrees or radians.
(For two dimensional vectors, just forget the z-coordinates and do the same calculations.)
Good luck,
John Doner
According to page 5 of this PDF, sum(a*b)
is the R command to find the dot product of vectors a
and b
, and sqrt(sum(a * a))
is the R command to find the norm of vector a
, and acos(x)
is the R command for the arc-cosine. It follows that the R code to calculate the angle between the two vectors is
theta <- acos( sum(a*b) / ( sqrt(sum(a * a)) * sqrt(sum(b * b)) ) )