I’ trying to generalize the computation of angles between two vectors in Angle between two vectors in R to the case of finding angles between all columns of a matrix X or between the columns of X and another matrix Y.
My attempt below fails, but I can’t figure out why
len <- function(X) {
if (!is.numeric(X)) stop("X must be numeric")
if (is.vector(X)) X <- matrix(X, ncol=1)
sqrt(colSums(X^2))
}
angle <- function(x, y, degree = TRUE) {
if(missing(y)) y <- x
if(is.vector(x) && is.atomic(x)) {
theta <- acos(x %*% y / (len(x) * len(y)))
}
else {
theta <- acos(t(x) %*% y / outer(len(x), len(y)))
}
if(degree) theta <- r2d(theta)
theta
}
These seem to work:
> x <- c(-2,1)
> y <- c(1,1)
> angle(x, y) # degrees
[,1]
[1,] 108.4349
> angle(x, y, degree = FALSE) # radians
[,1]
[1,] 1.892547
> angle(x) # for one arg case
[,1]
[1,] 1.207418e-06
These fail or are wrong:
X <- matrix(
c(1, 0, 1, 1, -2, 1),
ncol = 2,
byrow = TRUE)
Y <- matrix(
c(1, 1, -1, -1, 0, 0),
ncol = 2,
byrow = TRUE)
angle(X, Y)
angle(X)