flightpathr

Tools to analyze aircraft and flight path data.
git clone https://git.eamoncaddigan.net/flightpathr.git
Log | Files | Refs | README | LICENSE

coordsToBearing.R (1289B)


      1 #' Calculate the bearing between successive longitude/latitude points.
      2 #'
      3 #' @param longitude Latitude values.
      4 #' @param latitude Longitude values.
      5 #' @return The numeric vecotor giving the instantaneious bearing at each point
      6 #'   along the trajectory, in degrees. This will have the same length as the
      7 #'   trajectory, but the last element will be \code{NA}.
      8 #'
      9 #' @export
     10 coordsToBearing <- function(longitude, latitude) {
     11   trajectoryCoords <- cbind(longitude, latitude)
     12   numPoints <- nrow(trajectoryCoords)
     13 
     14   bearings <- geosphere::bearing(trajectoryCoords[1:(numPoints-1), 1:2],
     15                                  trajectoryCoords[2:numPoints, 1:2])
     16 
     17   # If successive points have the SAME lon/lat, geosphere::bearing() produces
     18   # meaningless output. Set these to NAs.
     19   distancesMeters <- geosphere::distHaversine(trajectoryCoords[1:(numPoints-1), 1:2],
     20                                               trajectoryCoords[2:numPoints, 1:2])
     21   bearings[distancesMeters < 1e-4] <- NA
     22 
     23   return(c(bearings, NA))
     24 }
     25 
     26 #' Calculate the signed difference between angles (in degrees)
     27 #'
     28 #' @param angle1 Source angle
     29 #' @param angle2 Target angle
     30 #' @return The signed difference between the two angles
     31 angleDiff <- function(angle1, angle2) {
     32   return(((angle2 - angle1) + 180) %% 360 - 180)
     33 }