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/dist bearing to centroid #74

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
28 changes: 28 additions & 0 deletions R/bearing_to_group_centroid.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#' Calculate absolute bearing to group centroid
#'
#' @param DT expects group_mean columns generated with group_centroid
#' @param coords character vector of column names for x, y
bearing_to_group_centroid <- function(DT, coords = NULL) {
pre <- 'group_mean_'

stopifnot(length(coords) == 2)

xcol <- first(coords)
ycol <- last(coords)
group_xcol <- paste0(pre, xcol)
group_ycol <- paste0(pre, ycol)

stopifnot(xcol %in% colnames(DT))
stopifnot(ycol %in% colnames(DT))
stopifnot(group_xcol %in% colnames(DT))
stopifnot(group_ycol %in% colnames(DT))

DT[, bearing_centroid := fifelse(
.SD[[xcol]] == .SD[[group_xcol]] &
.SD[[ycol]] == .SD[[group_ycol]],
NaN,
atan2(.SD[[group_ycol]] - .SD[[ycol]],
(.SD[[group_xcol]] - .SD[[xcol]]))
)]
return(DT[])
}
34 changes: 34 additions & 0 deletions R/distance_to_group_centroid.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#' Calculate distance to group centroid
#'
#' @param DT expects group_mean columns generated with group_centroid
#' @param coords character vector of column names for x, y
distance_to_group_centroid <- function(DT, coords, group = 'group',
return_rank = FALSE) {
pre <- 'group_mean_'

stopifnot(length(coords) == 2)

xcol <- first(coords)
ycol <- last(coords)
group_xcol <- paste0(pre, xcol)
group_ycol <- paste0(pre, ycol)

stopifnot(xcol %in% colnames(DT))
stopifnot(ycol %in% colnames(DT))
stopifnot(group_xcol %in% colnames(DT))
stopifnot(group_ycol %in% colnames(DT))
stopifnot(group %in% colnames(DT))


DT[, dist_group_centroid :=
sqrt((.SD[[xcol]] - .SD[[group_xcol]])^2 +
(.SD[[ycol]] - .SD[[group_ycol]])^2)]

if (return_rank) {
DT[, N_by_group := .N, by = c(group)]
DT[, rank_dist_group_centroid :=
data.table::frank(dist_group_centroid),
by = c(group)]
}
return(DT[])
}
Loading