[R] Converting from Continuous 2D Points to Continuous 2D Vectors

Sidoti, Salvatore A. sidoti.23 at buckeyemail.osu.edu
Thu Dec 17 22:25:20 CET 2015


Greetings!

I have a fairly large dataframe (df) with pathing information in the form of continuous x,y coordinates:

df$x
df$y

With these data, I would like to:
1. Calculate a set of continuous vectors
2. Determine the angle between each of these vectors (in degrees)
3. Count the number of angles in the dataframe that meet a certain threshold (i.e. <90°)

Here's what I've come up with so far:

### Function that calculates the angle between two vectors in 2D space:

angle <- function(x,y){ # x and y are vectors
  dot.prod <- x%*%y 
  norm.x <- norm(x,type="2")
  norm.y <- norm(y,type="2")
  theta <- acos(dot.prod / (norm.x * norm.y))
  (180*as.numeric(theta))/pi # returns the angle in degrees
}

### Test the function:
x <- as.matrix(c(2,1))
y <- as.matrix(c(1,2))
angle(t(x),y)
[1] 36.8699

Thank you!


More information about the R-help mailing list