Search code examples
rmathgeometrycomputational-geometry

Angle between two vectors in R


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


Solution

  • if you install/upload the library(matlib): there is a function called angle(x, y, degree = TRUE) where x and y are vectors. Note: if you have x and y in matrix form, use as.vector(x) and as.vector(y):

    library(matlib)
    matA <- matrix(c(3, 1), nrow = 2)  ##column vectors
    matB <- matrix(c(5, 5), nrow = 2)
    angle(as.vector(matA), as.vector(matB))  
    ##default in degrees, use degree = FALSE for radians