R/utils.R

Defines functions check_year_type check_src_year get_single_demo

Documented in check_src_year check_year_type get_single_demo

#' Get Demographics for an Entity
#'
#' Get demographics for a given entity or entities.
#' Most useful values to pass to ... include schools/school numbers,
#' school levels/types, grades, etc.
#'
#' @param df data
#' @param demovar a string. Variable to get demographics for (e.g. sex, ethnicity)
#' @param ... grouping variable(s)
#'
#' @return
#' @export
#'
get_single_demo <- function(df, demovar, ...) {

  suppressMessages(
    df %>%
      dplyr::count(.data[[demovar]], ...) %>%
      dplyr::add_count(..., wt = n) %>%
      dplyr::mutate(perc = n/nn) %>%
      dplyr::select(...,
           key = .data[[demovar]],
           perc)
  )

}

#' Wrapper to check the year when querying SRC tables
#'
#' @param year year to query
#'
#' @return
#' @export
#'
check_src_year <- function(year) {
  if (year < 2014) {
    rlang::abort(paste0("Fall membership data is not available before 2014"))
  }
}

#' Helper function to check type of year input and coerce if possible
#'
#' @param year value to check/coerce
#'
#' @return
#' @export
#'
check_year_type <- function(year) {
  if (typeof(year) %in% c("integer", "double")) {
    year
  } else if (typeof(year) == "character") {
    as.numeric(year)
  } else {
    rlang::abort(paste0("`year` must be numeric or coercible to numeric, not ", typeof(year)))
  }
}

##this currently doesn't work -- need to look into
#summarize_level_demos <- function(demos, ...) {

#  purrr::map(demos, ~get_single_demo(demovar = .x, ...)) #%>%
    #dplyr::bind_rows() %>%
    #tidyr::pivot_wider(
    #  names_from = key,
    #  values_from = perc,
    #  names_prefix = "sch_perc_"
    #) #%>%
    #janitor::clean_names() %>%
    #dplyr::mutate(dplyr::across(tidyselect::where(is.numeric), ~tidyr::replace_na(., 0)))

#}
ekholme-ccps/ccpsr documentation built on Aug. 17, 2021, 10:01 p.m.