diff --git a/R/read_erp.R b/R/read_erp.R index 2c72860..b2819a6 100644 --- a/R/read_erp.R +++ b/R/read_erp.R @@ -67,7 +67,7 @@ read_erp <- function(age_range = 0:100, } # Restrict the 'sex' argument to the valid choices - sex <- match.arg(sex) + sex <- match.arg(sex, several.ok = TRUE) # Restrict the states argument to valid choices but include abbreviations # Always return the full name if an abbreviation has been used. @@ -100,8 +100,24 @@ read_erp <- function(age_range = 0:100, path = path ) + x <- tidy_erp(erp_raw, + age_range, + sex) - x <- erp_raw %>% + x +} + +#' @keywords internal +#' @noRd +#' Tidy a table of ERP data downloaded with read_abs(cat_no = "3101.0") +#' @examples +#' x <- read_abs(cat_no = "3101.0") +#' tidy_erp(x) +#' +tidy_erp <- function(erp_raw, + age_range, + sex) { + erp_raw %>% dplyr::mutate( age = gsub("[^0-9]", "", .data$series), age = as.integer(.data$age), @@ -117,8 +133,6 @@ read_erp <- function(age_range = 0:100, dplyr::arrange(.data$state, .data$series_sex, .data$age, .data$date) %>% dplyr::select("date", "state", sex = "series_sex", "erp", "age") - - x } #' @keywords internal diff --git a/tests/testthat/test-read_erp.R b/tests/testthat/test-read_erp.R new file mode 100644 index 0000000..7fab441 --- /dev/null +++ b/tests/testthat/test-read_erp.R @@ -0,0 +1,41 @@ +test_that("read_erp() works", { + x <- read_erp() + + expect_is(x, "tbl_df") + expect_length(x, 5) + expect_gt(nrow(x), 40000) + expect_is(x$date, "Date") + expect_is(x$state, "character") + expect_is(x$sex, "character") + expect_is(x$erp, "numeric") + expect_is(x$age, "integer") + expect_equal(length(unique(x$state)), 9) + expect_equal(unique(x$sex), "Persons") + expect_equal(unique(x$age), 0:100) +}) + +test_that("tidy_erp() works with all permutations of parameters", { + raw_erp <- read_abs("3101.0") + + test_tidy_erp <- function(age_range, + sex, + erp_raw = raw_erp) { + x <- tidy_erp(erp_raw, + age_range, + sex) + + expect_is(x, "tbl_df") + expect_length(x, 5) + expect_equal(sort(unique(x$age)), sort(age_range)) + expect_equal(sort(unique(x$sex)), sort(sex)) + } + + test_tidy_erp(1:10, "Male") + test_tidy_erp(15, "Female") + test_tidy_erp(c(10, 50, 90), "Persons") + test_tidy_erp(0:100, + c("Male", "Female", "Persons")) + test_tidy_erp(1, + c("Female", "Male")) + +})