Angle between two vectors in R

Christian picture Christian · Dec 13, 2009 · Viewed 38.1k times · Source

What the most efficient way in the programming language R to calculate the angle between two vectors?

Answer

las3rjock picture las3rjock · Dec 13, 2009

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)) ) )