-
Notifications
You must be signed in to change notification settings - Fork 15
/
angle.R
51 lines (50 loc) · 1.35 KB
/
angle.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#
#' Angle between two vectors
#'
#' \code{angle} calculates the angle between two vectors.
#'
#' @param x a numeric vector
#' @param y a numeric vector
#' @param degree logical; should the angle be computed in degrees?
#' If \code{FALSE} the result is returned in radians
#'
#' @return a scalar containing the angle between the vectors
#' @seealso \code{\link{len}}
#' @export
#' @examples
#' x <- c(2,1)
#' y <- c(1,1)
#' angle(x, y) # degrees
#' angle(x, y, degree = FALSE) # radians
#'
#' # visually
#' xlim <- c(0,2.5)
#' ylim <- c(0,2)
#' # proper geometry requires asp=1
#' plot( xlim, ylim, type="n", xlab="X", ylab="Y", asp=1,
#' main = expression(theta == 18.4))
#' abline(v=0, h=0, col="gray")
#' vectors(rbind(x,y), col=c("red", "blue"), cex.lab=c(2, 2))
#' text(.5, .37, expression(theta))
#'
#'
#' ####
#' x <- c(-2,1)
#' y <- c(1,1)
#' angle(x, y) # degrees
#' angle(x, y, degree = FALSE) # radians
#'
#' # visually
#' xlim <- c(-2,1.5)
#' ylim <- c(0,2)
#' # proper geometry requires asp=1
#' plot( xlim, ylim, type="n", xlab="X", ylab="Y", asp=1,
#' main = expression(theta == 108.4))
#' abline(v=0, h=0, col="gray")
#' vectors(rbind(x,y), col=c("red", "blue"), cex.lab=c(2, 2))
#' text(0, .4, expression(theta), cex=1.5)
angle <- function(x, y, degree = TRUE) {
theta <- acos(x %*% y / (len(x) * len(y)))
if(degree) theta <- r2d(theta)
theta
}