Skip to content

Commit

Permalink
fst distance to leader
Browse files Browse the repository at this point in the history
  • Loading branch information
robitalec committed Jul 19, 2024
1 parent 39f921e commit d77538d
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions R/distance_to_leader.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#' Calculate distance to leader
#'
#' Leader as identified using group_leader by first position along
#' group axis of movement (return_rank = TRUE)
#'
#' @param DT
#' @param coords character vector of column names for x, y
#' @param group group column name generated by eg. group_pts
distance_to_leader <- function(DT, coords = c('x', 'y'), group = 'group') {
stopifnot(first(coords) %in% colnames(DT))
stopifnot(last(coords) %in% colnames(DT))
stopifnot(group %in% colnames(DT))
stopifnot('rank_dist_along_group_bearing' %in% colnames(DT))

DT[, temp_N_by_group := .N, by = c(group)]

check_has_leader <- DT[, .(has_leader = any(rank_dist_along_group_bearing == 1)),
by = c(group)][!(has_leader)]

if (check_has_leader[, .N > 0]) {
warning('groups found missing leader (rank_dist_along_group_bearing == 1): \n',
check_has_leader[, paste(group, collapse = ', ')])
}

DT[!group %in% check_has_leader$group,
dist_leader := fifelse(
temp_N_by_group > 1,
as.matrix(dist(cbind(.SD[[1]], .SD[[2]])))[, which(.SD[[3]] == 1)],
0
),
.SDcols = c(coords, 'rank_dist_along_group_bearing'),
by = c(group)]
DT[, temp_N_by_group := NULL]
return(DT)
}

0 comments on commit d77538d

Please sign in to comment.