R/add_populations.R

Defines functions add_populations

Documented in add_populations

#' Add Population Figures for all billions
#'
#' `add_populations()` adds relevant populations to each indicator and country,
#' so these can be used to calculate indicator-level aggregations of the
#' billions. The column specified by `population` will be generated and
#' filled with relevant populations for that country and indicator. If the column
#' already exists, only missing values will be replaced by the function.
#'
#' Essentially, the function wraps around `add_hep_populations()` and
#' `add_hpop_populations()` and add the country population to UHC indicators.
#'
#' As HEP indicators where population is relevant are all generated by billionaiRe,
#' the `transform_value_col` is required.
#'
#' @inherit transform_hpop_data return details params
#' @param pop_year Year used to pull in HPOP populations, defaults to 2025.
#' @param population Column name of column to create with population figures.
#' @inheritParams calculate_hpop_contributions
#' @inheritParams calculate_hpop_change_vector
#'
#' @family populations
#'
#' @export
add_populations <- function(df,
                            population = "population",
                            pop_year = 2025,
                            scenario_col = NULL,
                            transform_value_col = "transform_value",
                            ind_ids = billion_ind_codes("all", include_calculated = TRUE)) {

  assert_columns(df, "iso3", "ind", transform_value_col)
  assert_string(population, 1)
  assert_numeric(pop_year)

  df <- billionaiRe_add_columns(df, population, NA_real_)

  uhc_ind <- ind_ids[names(billion_ind_codes("uhc", include_calculated = TRUE))]
  uhc_ind <- uhc_ind[!names(uhc_ind) %in% "espar"]

  uhc_df <- df %>%
    dplyr::filter(.data[["ind"]] %in%  uhc_ind) %>%
    dplyr::mutate("{population}" := dplyr::case_when(
      is.na(.data[[population]]) ~ wppdistro::get_population(.data[["iso3"]], pop_year),
      TRUE ~ .data[[population]]
    ))

  hep_df <- df %>%
    dplyr::filter(.data[["ind"]] %in% ind_ids[names(billion_ind_codes("hep", include_calculated = TRUE))]) %>%
    add_hep_populations(scenario_col = scenario_col,
                        pop_year = pop_year,
                        population = population,
                        transform_value_col,
                        ind_ids = ind_ids[names(billion_ind_codes("hep", include_calculated = TRUE))])

  hpop_df <- df %>%
    dplyr::filter(.data[["ind"]] %in% ind_ids[names(billion_ind_codes("hpop", include_calculated = TRUE))]) %>%
    add_hpop_populations(pop_year = pop_year,
                         population = population,
                         ind_ids = billion_ind_codes("hpop", include_calculated = TRUE)
                         )

  dplyr::bind_rows(uhc_df, hep_df, hpop_df)

}
gpw13/billionaiRe documentation built on Sept. 27, 2024, 10:05 p.m.