What the most efficient way in the programming language R to calculate the angle between two vectors?
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)) ) )