R/flyangle.R

#' Track angle calculator
#'
#' Calculates the angle of the velocity vector in rad by comparing centroid location across \code{framelag}.
#'
#' For each timepoint t the velocity vector is calculated between \code{t-framelag/2} and \code{t+framelag+2}.
#' Currently this leaves \code{framelag/2 NA}s at the beginning and end of each track. This causes all sorts of problems
#' and may be best addressed somehow in the future.
#'
#' The angle is expressed in reference to the (arbitrary) coordinate system of the video and therefore this value is not overly useful.
#'
#' @param trx a track data frame (only requires CTrax output variables)
#' @param framelag the number of frames to derive velocity across; defaults to 6
#'
#' @return A numeric vector matching the structure of \code{trx} containing the angle value for each object and timepoint, or \code{NA}s when it can't be calculated.
#'
#' @export

flyangle <- function (trx, framelag=6)
{
  dx<- ave(trx$x,trx$id,FUN=function(a)
    c(rep(NA,floor(framelag/2)),diff(a,framelag),rep(NA,ceiling(framelag/2))))
  dy<- ave(trx$y,trx$id,FUN=function(a)
    c(rep(NA,floor(framelag/2)),diff(a,framelag),rep(NA,ceiling(framelag/2))))
  angle<-atan2(dx,dy)
  return(angle)
}
PaolaCognigni/CTraxHelper documentation built on May 7, 2019, 11:57 p.m.