From 590df6e52bdc5fea7209d2a3685151933dab2796 Mon Sep 17 00:00:00 2001 From: Izaak Jephson Date: Mon, 22 Jul 2024 12:09:12 +0100 Subject: [PATCH] Add test for bucket_other() --- R/summarise_data.R | 5 ++--- tests/testthat/helper.R | 2 +- tests/testthat/test-summarise_data.R | 8 ++++++++ 3 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 tests/testthat/test-summarise_data.R diff --git a/R/summarise_data.R b/R/summarise_data.R index a0c4f80..b07a381 100644 --- a/R/summarise_data.R +++ b/R/summarise_data.R @@ -10,12 +10,11 @@ #' @param other Value to be substituted for non-allowed values. Defaults to "Other" #' @export - bucket_other <- function(data, column, allowed_values, other = "Other"){ data %>% dplyr::mutate({{column}} := dplyr::case_when( - {{column}} %in% allowed_values ~ - {{column}}, + .data[[column]] %in% allowed_values ~ + .data[[column]], .default = other)) } diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index 3030ed8..5537152 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -21,7 +21,7 @@ create_test_data <- function(cols = tidyselect::everything()){ #' Helper function to create test data set 2 #' @export create_test_data_2 <- function(cols = tidyselect::everything()){ - dplyr::tibble(place = c("Aberdeen", "Glasgow", "Edinburgh", "Mull", "Ayr", "Perth", "Stirling", "Inverness", "Shetland", "Arran"), + dplyr::tibble(place = c("Aberdeen", "Glasgow", "Edinburgh", "Edinburgh", "Ayr", "Perth", "Stirling", "Inverness", "Glasgow", "Edinburgh"), month = c("January 2024", "February 2023", "September 2025", "October 2024", "March 2023", "February 2022", "September 2022", "December 2024", "November 2024", "April 2022"), count = c(4, 5, 7, 3, 6, 2, 7, 3, 4, 9), value = c(450, 399, 233, 736, 182, 433, 469, 932, 102, 377)) %>% diff --git a/tests/testthat/test-summarise_data.R b/tests/testthat/test-summarise_data.R new file mode 100644 index 0000000..895aa46 --- /dev/null +++ b/tests/testthat/test-summarise_data.R @@ -0,0 +1,8 @@ +test_that("bucket_other() aggregates any values not allowed in argument", { + test_data <- create_test_data_2(c("place", "count")) + expect_equal(bucket_other(data = test_data, + col = "place", + allowed_values = c("Glasgow", "Edinburgh")), + dplyr::tibble(place = c("Other", "Glasgow", "Edinburgh", "Edinburgh", "Other", "Other", "Other", "Other", "Glasgow", "Edinburgh"), + count = c(4, 5, 7, 3, 6, 2, 7, 3, 4, 9))) +})