Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/position along group axis #66

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions R/group_leader.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#' Position along group's mean bearing as leadership order
#'
#' Given the mean bearing of a group of animals, shifts the coordinate
#' system to a new origin at the group centroid and rotates the coordinate system
#' by the mean bearing. Returns the distance along the mean bearing as
#' the front-back position in group.
#'
#' @param DT
#' @param group_bearing group_bearing column name generated by eg. group_bearing,
#' default 'group_mean_bearing'
#' @param coords character vector of column names for x, y
#' @param group group column generated by eg. group_pts
#' @param return_rank if rank along mean bearing should also be returned,
#' used by functions bearing_to_leader, distance_to_leader
#' @param ties.method default: 'average', see ?data.table::frank. Note if
#' multiple individuals in a group have identical coordinates, they will
#' receive an average rank (eg. 1.5, 2.5) which may indicate some data cleaning
#' is required.
group_leader <- function(DT, group_bearing = 'group_mean_bearing', coords = c('x', 'y'),
group = 'group', return_rank = FALSE,
ties.method = 'average') {

xcol <- first(coords)
ycol <- last(coords)
xcol_group <- paste0('group_mean_', xcol)
ycol_group <- paste0('group_mean_', ycol)

stopifnot(group_bearing %in% colnames(DT))
stopifnot(group %in% colnames(DT))
stopifnot(xcol %in% colnames(DT))
stopifnot(ycol %in% colnames(DT))
stopifnot(xcol_group %in% colnames(DT))
stopifnot(ycol_group %in% colnames(DT))

DT[, dist_along_group_bearing :=
cos(.SD[[group_bearing]]) * (.SD[[xcol]] - .SD[[xcol_group]]) +
sin(.SD[[group_bearing]]) * (.SD[[ycol]] - .SD[[ycol_group]]),
by = .I]

if (return_rank) {
DT[, N_by_group := .N, by = c(group)]
DT[, rank_dist_along_group_bearing :=
data.table::frank(-dist_along_group_bearing, ties.method = ties.method),
by = c(group)]
}

return(DT)
}
Loading