From d77538d1d09dff5a6338538f98a9ee222a21d0f7 Mon Sep 17 00:00:00 2001 From: "Alec L. Robitaille" Date: Fri, 19 Jul 2024 12:00:52 -0300 Subject: [PATCH] fst distance to leader --- R/distance_to_leader.R | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 R/distance_to_leader.R diff --git a/R/distance_to_leader.R b/R/distance_to_leader.R new file mode 100644 index 0000000..66cfb8c --- /dev/null +++ b/R/distance_to_leader.R @@ -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) +}