This function computes the relative angle between subsequent headings (thus: turning angles), in the range (\(-\pi\), \(\pi\)), where negative angles are turns to the left (compared to the initial movement heading), and positive angles turns to the right. Angles of 0 mean straight forward locomotion, and an angle of (-)\(\pi\) is a 180 degrees turn.

tangle <- function(x) {
  # Checks
  if(missing(x)) { stop("supply x") }
  
  # compute relative angles
  n <- length(x)
  ref.angle <- x[-n]
  x <- x[-1]
  x <- x %% (2*pi)
  ref.angle <- ref.angle %% (2*pi)
  rangle <- x - ref.angle
  
  # Set NA temporarily to 0 and set angles to range (-pi,pi) degrees or 
  rangleNA <- is.na(rangle)
  rangle[rangleNA] <- 0
  rangle[rangle >  pi] <- rangle[rangle >  pi] - 2*pi
  rangle[rangle < -pi] <- rangle[rangle < -pi] + 2*pi
  
  # Reset NA values and have first relative angle be NA
  rangle[rangleNA] <- NA
  rangle <- c(NA, rangle)
  
  # Return output
  return(rangle)
}