From 234fcb15ed1de846a39c59930598cdf0cad978b6 Mon Sep 17 00:00:00 2001 From: Joe Roe Date: Thu, 17 Oct 2024 15:11:08 +0200 Subject: [PATCH] Normalise value of cal_interpolate() --- R/cal.R | 8 +++++++- R/cal_aggregate.R | 2 +- tests/testthat/test-cal.R | 4 ++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/R/cal.R b/R/cal.R index e2f04df..5f85fb4 100644 --- a/R/cal.R +++ b/R/cal.R @@ -177,8 +177,14 @@ cal_age_common <- function(x, resolution = 1) { #' Interpolate a cal vector over the given range #' +#' Result is normalised +#' #' @noRd #' @keywords internal cal_interpolate <- function(x, range = cal_age_common(x)) { - new_cal(furrr::future_map(vec_data(x), \(x) approx_df(x, range, ties = "ordered"))) + new_cal(furrr::future_map(vec_data(x), function(x) { + x <- approx_df(x, range, ties = "ordered") + x$pdens <- x$pdens / sum(x$pdens, na.rm = TRUE) + x + })) } \ No newline at end of file diff --git a/R/cal_aggregate.R b/R/cal_aggregate.R index 78fc305..5449c9f 100644 --- a/R/cal_aggregate.R +++ b/R/cal_aggregate.R @@ -32,7 +32,7 @@ cal_sum <- function(x, range = cal_age_common(x), normalise = FALSE, ...) { x <- cal_interpolate(x, range) pdens_sum <- furrr::future_pmap_dbl(cal_pdens(x), \(...) sum(..., na.rm = TRUE)) - if (isTRUE(normalise)) pdens_sum <- pdens_sum / sum(pdens_sum) + if (isTRUE(normalise)) pdens_sum <- pdens_sum / sum(pdens_sum, na.rm = TRUE) new_cal(list(data.frame(age = cal_age(x)[[1]], pdens = pdens_sum))) } \ No newline at end of file diff --git a/tests/testthat/test-cal.R b/tests/testthat/test-cal.R index 38b1d9c..ab6d1e9 100644 --- a/tests/testthat/test-cal.R +++ b/tests/testthat/test-cal.R @@ -16,3 +16,7 @@ test_that("cal_age_common() returns a yr vector", { # TODO: somehow test the expected length? expect_vector(cal_age_common(y), y_yr_ptype) }) + +test_that("cal_interpolate() is normalised", { + expect_equal(sum(cal_pdens(cal_interpolate(x))[[1]]), 1) +})