From 42f1ff98be5a6c1c72e8da24e57c5b3b9935d551 Mon Sep 17 00:00:00 2001 From: "Alec L. Robitaille" Date: Fri, 19 Jul 2024 12:04:21 -0300 Subject: [PATCH] fst group centroid --- R/group_centroid.R | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 R/group_centroid.R diff --git a/R/group_centroid.R b/R/group_centroid.R new file mode 100644 index 00000000..2efd273f --- /dev/null +++ b/R/group_centroid.R @@ -0,0 +1,22 @@ +#' Group centroid +#' +#' Mean of individual locations in each group +#' +#' @param DT expecting group generated with eg. group_pts +#' @param coords character vector of column names for x, y +#' @param group group column default 'group' +#' @param na.rm if NAs should be removed in calculating mean location +group_centroid <- function(DT, coords, group = 'group', na.rm = FALSE) { + stopifnot(length(coords) == 2) + + xcol <- first(coords) + ycol <- last(coords) + + stopifnot(xcol %in% colnames(DT)) + stopifnot(ycol %in% colnames(DT)) + stopifnot(group %in% colnames(DT)) + + DT[, paste0('group_mean_', xcol) := mean(.SD[[xcol]], na.rm = na.rm), by = c(group)] + DT[, paste0('group_mean_', ycol) := mean(.SD[[ycol]], na.rm = na.rm), by = c(group)] + return(DT[]) +} \ No newline at end of file