| Title: | Data Loading, Validation, and Reporting for Countdown 2030 |
|---|---|
| Description: | cd2030.core is an R package for managing and validating data formatted according to Countdown 2030 standards. It provides tools for data loading, cleaning, and validation, detecting issues like missing values, inconsistencies, outliers, and ratio anomalies. The package ensures compliance with Countdown 2030 guidelines and generates standardized data quality reports, enabling users to focus on analysis and interpretation. |
| Authors: | David Kariuki [aut, cre] (ORCID: <https://orcid.org/0009-0003-6159-1107>), Martin Mutua [aut], Peter Kaberia [aut], Godfrey Adero [aut], Rornald Muhumuza [aut], African Population and Health Research Center (APHRC) [cph, fnd] |
| Maintainer: | David Kariuki <[email protected]> |
| License: | AGPL (>= 3) |
| Version: | 1.4.4 |
| Built: | 2026-10-12 11:13:21 UTC |
| Source: | https://github.com/damurka/cd2030.core |
add_mad_med_columns calculates and appends the median and Median Absolute
Deviation (MAD) for specified indicators in a dataset. These statistics are
calculated per group, allowing the user to dynamically group data (e.g., by
district) and exclude data from the most recent year in the dataset.
add_mad_med_columns(.data, indicators, group_by = "district")add_mad_med_columns(.data, indicators, group_by = "district")
.data |
A |
indicators |
A character vector specifying the names of the indicator columns for which the median and MAD should be calculated. |
group_by |
A character string or vector specifying the column(s) to group
by when calculating the median and MAD (default is |
The median and MAD are calculated for each group specified by group_by.
Only data from years prior to the most recent year in the dataset are considered.
Missing values in the calculated statistics are replaced using robust_max(),
ensuring that meaningful fallback values are provided.
A tibble with additional columns for each indicator, named
{indicator}_med and {indicator}_mad, containing the calculated median
and MAD, respectively.
add_outlier5std_column() for generating outlier flags based on these columns.
robust_max() for calculating max value
## Not run: # Add median and MAD columns for 'indicator1' add_mad_med_columns(data, indicators = "indicator1", group_by = "district" ) ## End(Not run)## Not run: # Add median and MAD columns for 'indicator1' add_mad_med_columns(data, indicators = "indicator1", group_by = "district" ) ## End(Not run)
add_missing_column assesses data quality by identifying missing values for
specified health indicators. It generates new columns for each indicator,
flagging values as 'Missing' (1) or 'Non-Missing' (0) to support downstream
quality control and analysis.
add_missing_column(.data, indicators)add_missing_column(.data, indicators)
.data |
A data frame containing health indicator data. |
indicators |
A character vector specifying the names of the indicator columns to analyze for outliers. |
Missingness Assessment:
Each indicator is processed to flag missing values (NA) with 1 (missing)
or 0 (non-missing). The resulting columns are prefixed with mis_ followed
by the original indicator name (e.g., mis_indicator1).
Group Preservation:
The output retains the district and year columns to ensure grouping information
remains intact.
A data frame containing:
Missingness Flags:
For each indicator, a column prefixed with mis_ indicating missingness (1 for
missing, 0 otherwise).
district and year columns to maintain grouping information.
## Not run: # dd missing value flags for all indicators add_missing_column(data) ## End(Not run)## Not run: # dd missing value flags for all indicators add_missing_column(data) ## End(Not run)
add_outlier5std_column calculates and appends outlier flags for specified
indicators in a dataset. An outlier is defined as a value falling outside the
range defined by the median ± 5 times the Median Absolute Deviation (MAD).
This method is applied on a per-group basis, allowing flexibility for grouping
by columns like district.
add_outlier5std_column(.data, indicators, group_by = "district")add_outlier5std_column(.data, indicators, group_by = "district")
.data |
A |
indicators |
A character vector specifying the names of the indicator columns to analyze for outliers. |
group_by |
A character string or vector specifying the column(s) to group
by when calculating the median and MAD (default is |
Median and MAD Calculation: For each indicator, the median and MAD are calculated using data from years prior to the most recent year in the dataset. The last year is excluded to prevent potential contamination of the baseline statistics.
Outlier Definition: A value is flagged as an outlier if it falls outside the range: Lower Bound = median - 5 * MAD Lower Bound = median + 5 * MAD
Grouping:
Calculations are performed separately for each group specified by the
group_by parameter.
Generated Columns:
For each indicator, the function generates an outlier flag column named
{indicator}_outlier5std. The column contains 1 if the value is an outlier
and 0 otherwise.
A tibble with additional columns for each indicator, named
{indicator}_outlier5std, containing a value of 1 if the observation is
an outlier and 0 otherwise.
add_mad_med_columns() for computing and appending the median and MAD columns.
## Not run: # Add missing value flags for all indicators add_outlier5std_column(data, indicators = "indicator1", group_by = "district" ) ## End(Not run)## Not run: # Add missing value flags for all indicators add_outlier5std_column(data, indicators = "indicator1", group_by = "district" ) ## End(Not run)
The adjust_service_data function processes DHIS-2 health service data, correcting
for incomplete reporting, applying k-factor adjustments for accurate scaling, and managing
outliers for consistency in data analysis. This standardization supports reliable
comparisons in immunization coverage and health service utilization studies.
adjust_service_data( .data, adjustment = c("default", "custom", "none"), k_factors = NULL, settings = NULL, steps = FALSE )adjust_service_data( .data, adjustment = c("default", "custom", "none"), k_factors = NULL, settings = NULL, steps = FALSE )
.data |
A |
adjustment |
A character string specifying the type of adjustment to apply:
|
k_factors |
A named numeric vector of custom k-factor values between 0 and 1
for each indicator group (e.g., |
settings |
The adjustment settings ( |
steps |
|
Prepares service data through a series of steps to ensure data quality and consistency:
Validation: Checks the structure of .data and ensures that the adjustment
argument is valid. For custom adjustments, k_factors must be specified and contain valid values.
k-Factor Defaults: Default k-factor values are set to 0.25 for each indicator group,
unless overridden by user-provided values in k_factors.
Reporting Completeness: Flags any district-year reporting rates below 75% and imputes missing data using district-level medians to account for reporting inconsistencies.
k-Factor Scaling: Adjusts service counts based on the k-factor and reporting rate using the following scaling formula:
where ReportingRate is the reporting rate in percent, and k is the k-factor for the indicator group.
Outlier Detection: Identifies and flags extreme outliers using Hampel's X84 method, marking values that exceed 5 Median Absolute Deviations (MAD) from the median.
Data Imputation: Replaces remaining missing values with district-level medians to ensure data completeness.
A cd_adjusted_data object containing adjusted service data, where outliers are flagged
and managed, and missing values are imputed.
new_countdown() for creating cd_data objects and generate_adjustment_values()
for generating adjustment summaries.
## Not run: # Default adjustment adjusted_data <- adjust_service_data(data, adjustment = "default") # Custom adjustment with specific k-factors custom_k <- c( anc = 0.3, idelv = 0.2, pnc = 0.35, vacc = 0.4, opd = 0.3, ipd = 0.25 ) adjusted_data_custom <- adjust_service_data(data, adjustment = "custom", k_factors = custom_k ) # No adjustment unadjusted_data <- adjust_service_data(data, adjustment = "none") ## End(Not run)## Not run: # Default adjustment adjusted_data <- adjust_service_data(data, adjustment = "default") # Custom adjustment with specific k-factors custom_k <- c( anc = 0.3, idelv = 0.2, pnc = 0.35, vacc = 0.4, opd = 0.3, ipd = 0.25 ) adjusted_data_custom <- adjust_service_data(data, adjustment = "custom", k_factors = custom_k ) # No adjustment unadjusted_data <- adjust_service_data(data, adjustment = "none") ## End(Not run)
The page that shows what the adjustment changed, one indicator at a time. A chart sets each
year's reported count beside the adjusted count, which is made of its parts (completeness,
outliers and missing values), and a table gives the same numbers with the change in percent. A
step the indicator does not get is marked "Off". Above the chart, the page lists the adjustment's
rules as the reports' footnote gives them (adjustment_settings_footnote()) and says whether the
data has been adjusted.
adjustment_changes_ui(id, i18n) adjustment_changes_server(id, cache, i18n, active = reactive(TRUE))adjustment_changes_ui(id, i18n) adjustment_changes_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
The indicator is chosen with the card's tabs (the app's adjustment_indicators setting) or with
the filter for the other indicators, which wins while it has a value. The area filter is every
area, one region or one district. The page reads data_with_excluded_years,
adjustment_settings, countdown_data and adjusted_flag from the dataset, and works the
numbers out with generate_adjustment_values().
adjustment_changes_ui() returns the page's UI as Shiny tags.
adjustment_changes_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_adjustment_changes", ui = adjustment_changes_ui, server = adjustment_changes_server, title = "title_adjust_changes", section = "lbl_nav_section_quality", subtitle = "sub_adjust_changes" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_adjustment_changes", ui = adjustment_changes_ui, server = adjustment_changes_server, title = "title_adjust_changes", section = "lbl_nav_section_quality", subtitle = "sub_adjust_changes" ) ## End(Not run)
The numbers the Data Adjustment page shows beside its settings, from the same computations as the check pages
(Reporting rate, Outlier detection, Data completeness): each indicator group's national reporting rate in year
and how many districts report below threshold; each indicator's outlier months (more than 5 x MAD from the
district's median) and empty months; each region's and district's lowest group reporting rate in year.
adjustment_evidence( .data, threshold = .cd_method$data_quality$reporting_threshold, year = NULL )adjustment_evidence( .data, threshold = .cd_method$data_quality$reporting_threshold, year = NULL )
.data |
A |
threshold |
Numeric. The performance threshold (in percent) of the Reporting rate page. |
year |
The year of the reporting rates (by default the latest). |
A list: year, threshold, groups (named by group: rr, below), indicators (named by indicator:
outliers, missing, months), areas (a list of list(region, rr, districts = list(list(name, rr)))).
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) evidence <- adjustment_evidence(data) str(evidence$groups$opd) str(evidence$indicators$penta3) # Against a stricter threshold, for an earlier year adjustment_evidence(data, threshold = 95, year = 2021)$groups$opdpath <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) evidence <- adjustment_evidence(data) str(evidence$groups$opd) str(evidence$indicators$penta3) # Against a stricter threshold, for an earlier year adjustment_evidence(data, threshold = 95, year = 2021)$groups$opd
Validates settings as the Data Adjustment page sends them (JSON read with simplifyVector = FALSE) and returns them
in one shape: numbers as numbers, flags as logicals, empty maps as empty lists, unknown groups, indicators and
levels refused.
adjustment_settings_check(settings)adjustment_settings_check(settings)
settings |
The settings list. |
The settings, tidied. An error says what is wrong.
# Settings as they arrive from JSON: numbers and flags inside lists settings <- list( removed_years = list(2020, 2021), everywhere = list(group_k = list(anc = 0.1), outliers = list(penta3 = list(FALSE))), areas = list(list(area = "Coast", level = "adminlevel_1", all_missing = list(FALSE))) ) str(adjustment_settings_check(settings)) # What is wrong is refused with an error try(adjustment_settings_check(list(everywhere = list(group_k = list(anc = 2)))))# Settings as they arrive from JSON: numbers and flags inside lists settings <- list( removed_years = list(2020, 2021), everywhere = list(group_k = list(anc = 0.1), outliers = list(penta3 = list(FALSE))), areas = list(list(area = "Coast", level = "adminlevel_1", all_missing = list(FALSE))) ) str(adjustment_settings_check(settings)) # What is wrong is refused with an error try(adjustment_settings_check(list(everywhere = list(group_k = list(anc = 2)))))
Every indicator group adjusted for completeness with the method's k (0.25), outliers corrected and missing values filled everywhere, no year or area removed.
adjustment_settings_default(k = .cd_method$adjustment$k, groups = NULL)adjustment_settings_default(k = .cd_method$adjustment$k, groups = NULL)
k |
The k of every group (by default the method's, |
groups |
The groups that have a k (by default the app's, |
The settings list (see adjust_service_data()).
settings <- adjustment_settings_default() str(settings) # No completeness adjustment for any group adjustment_settings_default(k = 0)$everywhere$group_ksettings <- adjustment_settings_default() str(settings) # No completeness adjustment for any group adjustment_settings_default(k = 0)$everywhere$group_k
Writes the adjustment settings out in sentences, for the footnote of a report: the years and areas removed, then the rules that apply everywhere and those of each area (k factors, and whether outliers are corrected and missing values filled).
adjustment_settings_footnote( settings, group_labels = NULL, indicator_labels = NULL )adjustment_settings_footnote( settings, group_labels = NULL, indicator_labels = NULL )
settings |
The settings list. |
group_labels, indicator_labels
|
Named character: how groups and indicators are called (by default their ids). |
A character vector, one sentence per rule. The Countdown default is one rule (each group's k, everywhere); settings that change nothing give none.
settings <- adjustment_settings_default(k = 0.1, groups = c("anc", "vacc")) settings$removed_years <- 2020 settings$everywhere$outliers <- list(penta3 = FALSE) settings$areas <- list(list(area = "Coast", level = "adminlevel_1", all_missing = FALSE)) adjustment_settings_footnote(settings) # With the names a report uses adjustment_settings_footnote( settings, group_labels = c(anc = "Antenatal care", vacc = "Immunization"), indicator_labels = c(penta3 = "Penta 3") )settings <- adjustment_settings_default(k = 0.1, groups = c("anc", "vacc")) settings$removed_years <- 2020 settings$everywhere$outliers <- list(penta3 = FALSE) settings$areas <- list(list(area = "Coast", level = "adminlevel_1", all_missing = FALSE)) adjustment_settings_footnote(settings) # With the names a report uses adjustment_settings_footnote( settings, group_labels = c(anc = "Antenatal care", vacc = "Immunization"), indicator_labels = c(penta3 = "Penta 3") )
A dataset saved before the settings existed has only its k per group and its removed years: they become the settings, everything else as the default.
adjustment_settings_from_k(k_factors = NULL, excluded_years = numeric())adjustment_settings_from_k(k_factors = NULL, excluded_years = numeric())
k_factors |
Named numeric k per group. |
excluded_years |
Numeric years removed. |
The settings list.
settings <- adjustment_settings_from_k(c(anc = 0.1, vacc = 0), excluded_years = 2020) settings$everywhere$group_k settings$removed_yearssettings <- adjustment_settings_from_k(c(anc = 0.1, vacc = 0), excluded_years = 2020) settings$everywhere$group_k settings$removed_years
Whether completeness (a k above 0), outlier correction and filling missing values apply to an indicator in at least one district of the data (or of one area), with the settings: a step no district gets is off.
adjustment_steps_used( settings, .data, indicator, area = NULL, level = c("adminlevel_1", "district") )adjustment_steps_used( settings, .data, indicator, area = NULL, level = c("adminlevel_1", "district") )
settings |
The settings list. |
.data |
A |
indicator |
The indicator. |
area, level
|
One area only (as |
A named logical: completeness, outliers, missing.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) settings <- adjustment_settings_default() adjustment_steps_used(settings, data, "penta3") # A region with its own settings: no completeness adjustment, outliers left as they are settings$areas <- list( list(area = "Coast", level = "adminlevel_1", group_k = list(vacc = 0), all_outliers = FALSE) ) adjustment_steps_used(settings, data, "penta3", area = "Coast") adjustment_steps_used(settings, data, "penta3")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) settings <- adjustment_settings_default() adjustment_steps_used(settings, data, "penta3") # A region with its own settings: no completeness adjustment, outliers left as they are settings$areas <- list( list(area = "Coast", level = "adminlevel_1", group_k = list(vacc = 0), all_outliers = FALSE) ) adjustment_steps_used(settings, data, "penta3", area = "Coast") adjustment_steps_used(settings, data, "penta3")
The fitted coverage by year (2010 to 2030), in percent like the other coverage tables: the median with its 95% and 80% intervals. A sub-national model gives a row per region and year.
bayes_model_estimates(model)bayes_model_estimates(model)
model |
A model from |
A tibble: indicator, adminlevel_1 (a sub-national model only), year, estimate, lower and
upper (95%), lower_80 and upper_80.
## Not run: # `cache` is a dataset with adjusted data; fitting needs the Bayesian model packages model <- cache$get_bayes_model("national", "penta3") estimates <- bayes_model_estimates(model) estimates[estimates$year >= 2020, c("year", "estimate", "lower", "upper")] # a sub-national model has a row per region and year regions <- bayes_model_estimates(cache$get_bayes_model("adminlevel_1", "penta3")) regions[regions$year == 2023, ] ## End(Not run)## Not run: # `cache` is a dataset with adjusted data; fitting needs the Bayesian model packages model <- cache$get_bayes_model("national", "penta3") estimates <- bayes_model_estimates(model) estimates[estimates$year >= 2020, c("year", "estimate", "lower", "upper")] # a sub-national model has a row per region and year regions <- bayes_model_estimates(cache$get_bayes_model("adminlevel_1", "penta3")) regions[regions$year == 2023, ] ## End(Not run)
The server an app lists for its Bayesian pages in its page registry. It calls bayesian_server()
with an active that also starts the background workers (cd_start_bayes_workers()) each time
it is read as TRUE, which happens first when the page is opened with data loaded. Starting them
a second time does nothing, so the workers are started once and only for sessions that open the
page.
bayesian_page_server(id, cache, i18n, admin_level, active = reactive(TRUE))bayesian_page_server(id, cache, i18n, admin_level, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
cache |
A reactive that returns the dataset, a CacheConnection. |
i18n |
The app's translator (a |
admin_level |
A string, not a reactive: the level the models are fitted at, |
active |
A reactive that is |
What bayesian_server() returns: a reactive that holds the key of the tab shown (an
indicator's name, or "custom").
## Not run: # the page's entry in an app's page registry; server_args gives the admin level cd_page_def( id = "bayesian_national", ui = bayesian_ui, server = bayesian_page_server, title = "title_bayesian_analysis", section = "title_bayesian_analysis", subtitle = "sub_bayesian", server_args = list("national") ) # the same page at admin level 1 is a second entry: id = "bayesian_subnational" and # server_args = list("adminlevel_1") ## End(Not run)## Not run: # the page's entry in an app's page registry; server_args gives the admin level cd_page_def( id = "bayesian_national", ui = bayesian_ui, server = bayesian_page_server, title = "title_bayesian_analysis", section = "title_bayesian_analysis", subtitle = "sub_bayesian", server_args = list("national") ) # the same page at admin level 1 is a second entry: id = "bayesian_subnational" and # server_args = list("adminlevel_1") ## End(Not run)
The Bayesian coverage model page, shared by the apps and used at national level and at admin
level 1. It has one card of charts with a tab for each indicator the app lists
(cd_cfg("bayes_indicators"), by default cd_bayes_indicators), the only ones the model takes; each tab plots
the model's coverage estimates by year. A model takes minutes to fit, so the fit runs in a
background worker (cd_bayes_fit_task()) and the chart shows its loader meanwhile. A fit starts
only when its tab is shown, from the dataset's bayes_model_inputs(); the result is kept in the
dataset (keep_bayes_model()) and read back with bayes_model_cached(), so it is fitted once
for an admin level, indicator and denominator. While the model's packages are missing
(cd_bayes_packages_missing()) the page shows a notice and fits nothing: inside DataSuite the
notice has a button that asks it to install them, elsewhere it shows the R command to run.
bayesian_ui(id, i18n, label) bayesian_server(id, cache, i18n, admin_level, active = reactive(TRUE))bayesian_ui(id, i18n, label) bayesian_server(id, cache, i18n, admin_level, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
label |
Not used. |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A string, not a reactive: the level the models are fitted at, |
active |
A reactive that is |
At admin level 1 the page has two filters: the region (every region compared in one year, each with its
model estimate and its facility-data value, or one region followed over the years as the national page
follows the country) and the year the regions are compared in. The national page has none. Apps register
the page with bayesian_page_server(), which also starts the workers.
bayesian_ui() returns the page's UI as Shiny tags. bayesian_server() returns a
reactive that holds the key of the tab shown: an indicator's name, or "custom".
## Not run: # a page of your own with the same charts: start the workers, then call the server. # The id must be a page in the app's page registry. my_bayes_ui <- function(id, i18n) bayesian_ui(id, i18n) my_bayes_server <- function(id, cache, i18n, active = reactive(TRUE)) { cd_start_bayes_workers() bayesian_server(id, cache, i18n, "adminlevel_1", active = active) } ## End(Not run)## Not run: # a page of your own with the same charts: start the workers, then call the server. # The id must be a page in the app's page registry. my_bayes_ui <- function(id, i18n) bayesian_ui(id, i18n) my_bayes_server <- function(id, cache, i18n, active = reactive(TRUE)) { cd_start_bayes_workers() bayesian_server(id, cache, i18n, "adminlevel_1", active = active) } ## End(Not run)
The definition of one public member of CacheConnection: what it holds or returns in the methodology's terms, its
kind (data, setting, reference, mapping, check, value, store, state, method, action), its grain
(what one row is) and key columns, its unit, where the user sets it in the app (set_on) and which pages show it
(shown_on), the methodology docs section it comes from (method), the defaults it follows (ids of
cd_methodology_defaults()), and what it is computed from (depends_on). Columns are described from their names
by the data dictionary, not here. status is "draft" (with a note) where the definition is not certain.
cache_manifest() includes every member's definition.
cache_definition(name = NULL)cache_definition(name = NULL)
name |
A member name, e.g. |
A list (one definition), a named list of all of them, or NULL when name is not a public member.
cache_definition("adjusted_data")$whatcache_definition("adjusted_data")$what
Every public member of CacheConnection – method or active binding – with its arguments (defaults, and the
values an argument may take when the code says), its documentation, whether it writes to the dataset, whether a
custom chart may draw from it, and its definition (what the data point is, see cache_definition()); plus the
report kinds. Read from the installed package, so it always matches the code; countdown-analytics builds its guide
for the AI from it.
cache_manifest()cache_manifest()
A list (JSON-able with jsonlite::toJSON(auto_unbox = TRUE)): package, version, generatedAt,
members and reportKinds.
m <- cache_manifest() length(m$members)m <- cache_manifest() length(m$members)
calculate_average_reporting_rate() computes the average reporting rate for
each indicator by year and administrative level. For adminlevel_1, you can
limit the results to a single region.
calculate_average_reporting_rate( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL )calculate_average_reporting_rate( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL )
.data |
A tibble of class |
admin_level |
Character. One of |
region |
Optional. Name of a specific region ( |
A tibble of class cd_average_reporting_rate.
## Not run: calculate_average_reporting_rate(data, admin_level = "adminlevel_1") calculate_average_reporting_rate(data, admin_level = "adminlevel_1", region = "Nairobi") ## End(Not run)## Not run: calculate_average_reporting_rate(data, admin_level = "adminlevel_1") calculate_average_reporting_rate(data, admin_level = "adminlevel_1", region = "Nairobi") ## End(Not run)
Computes yearly percentage of non-missing values for each indicator, along with overall completeness summaries.
calculate_completeness_summary( .data, admin_level = c("national", "adminlevel_1", "district"), threshold = .cd_method$data_quality$reporting_threshold, region = NULL )calculate_completeness_summary( .data, admin_level = c("national", "adminlevel_1", "district"), threshold = .cd_method$data_quality$reporting_threshold, region = NULL )
.data |
A |
admin_level |
One of |
threshold |
Numeric. The performance threshold (in percent) stored as an
attribute on the result and used when plotting. Default is |
region |
Optional name of an |
A cd_completeness_summary tibble:
One row per year and group
mis_<indicator> columns with % non-missing values
mean_mis_all summarizing all indicators
## Not run: calculate_completeness_summary(data) ## End(Not run)## Not run: calculate_completeness_summary(data) ## End(Not run)
calculate_coverage integrates immunization coverage data from three sources:
DHIS2 (District Health Information Software), survey-based estimates, and
WUENIC (WHO-UNICEF estimates). The combined dataset is prepared for analysis
at various administrative levels.
calculate_coverage(.data, survey_data, wuenic_data, subnational_map = NULL)calculate_coverage(.data, survey_data, wuenic_data, subnational_map = NULL)
.data |
A |
survey_data |
A data frame containing survey-based immunization estimates. |
wuenic_data |
A data frame containing WHO-UNICEF (WUENIC) coverage estimates. |
subnational_map |
(Optional) A data frame mapping subnational regions to
parent regions, required for subnational-level analyses. Default is |
A cd_coverage data frame containing harmonized coverage estimates
for each year from DHIS2, WUENIC, and survey data. Includes metadata for
administrative levels, regions, and denominators.
## Not run: calculate_coverage(precomputed_data, survey_df, wuenic_df) ## End(Not run)## Not run: calculate_coverage(precomputed_data, survey_df, wuenic_df) ## End(Not run)
Calculates trend-adjusted and subnationally-redistributed coverage estimates using the DTP1-derived denominator logic described in CD2030. It estimates coverage over time based on changes in DHIS2 population counts, while preserving subnational proportions from the base year.
calculate_derived_coverage(.data, indicator)calculate_derived_coverage(.data, indicator)
.data |
A |
indicator |
A character string specifying the indicator to calculate coverage for. |
This allows estimating:
Trends over time in coverage
Subnational inequities
A cd_derived_coverage tibble with columns for old and new coverage estimates.
## Not run: calculate_derived_coverage(population_metrics, "penta1") ## End(Not run)## Not run: calculate_derived_coverage(population_metrics, "penta1") ## End(Not run)
Calculates yearly % of districts with complete data for each indicator.
calculate_district_completeness_summary(.data, region = NULL)calculate_district_completeness_summary(.data, region = NULL)
.data |
A |
region |
Optional name of an |
A cd_missing_district tibble:
One row per year
% non-missing per indicator
mean_mis_all, mean_mis_four summaries
## Not run: calculate_district_completeness_summary(data) ## End(Not run)## Not run: calculate_district_completeness_summary(data) ## End(Not run)
Calculates the yearly percentage of districts without extreme outliers for each health indicator. Flags are based on the Hampel X84 method (beyond 5 MAD from median).
calculate_district_outlier_summary(.data, region = NULL)calculate_district_outlier_summary(.data, region = NULL)
.data |
A |
region |
Optional. Filter results to a specific |
Aggregates by district and year, using the max flag per group.
Computes percent of non-outliers per indicator.
Returns yearly summaries including:
Per-indicator non-outlier rates
mean_out_all: all indicators
mean_out_four: excludes IPD
All results are rounded to two decimals.
A cd_district_outliers_summary tibble.
## Not run: calculate_district_outlier_summary(data) ## End(Not run)## Not run: calculate_district_outlier_summary(data) ## End(Not run)
Calculates and summarizes the adequacy of specified indicator ratios by year, evaluating the consistency of key health indicators across districts. It computes the percentage of districts meeting the adequacy criteria for each indicator ratio, based on the specified range.
calculate_district_ratios_summary(.data)calculate_district_ratios_summary(.data)
.data |
A data frame containing indicator data by district and year.
The data frame should include all indicators specified in |
The function dynamically calculates ratios between the specified indicator pairs.
For each year, it computes the percentage of districts where the calculated ratio for each indicator pair falls within the adequate range.
The summary table aids in monitoring indicator consistency across districts and over time, providing insights into areas where health service delivery may vary.
A tibble of class cd_district_ratios_summary, containing the summary of
adequacy checks by year. Each column represents the percentage of districts
meeting the adequacy criteria for the specified ratio, with overall metrics
included for data interpretation and quality monitoring.
## Not run: # Calculate adequacy summary for ANC1/Penta1 and other indicator ratios calculate_district_ratios_summary(cd_data) ## End(Not run)## Not run: # Calculate adequacy summary for ANC1/Penta1 and other indicator ratios calculate_district_ratios_summary(cd_data) ## End(Not run)
calculate_district_reporting_rate Calculates the percentage of districts that
meet or exceed a specified reporting rate threshold for each indicator, by year.
Also computes a yearly average across all indicators.
calculate_district_reporting_rate( .data, threshold = .cd_method$data_quality$reporting_threshold, region = NULL )calculate_district_reporting_rate( .data, threshold = .cd_method$data_quality$reporting_threshold, region = NULL )
.data |
A tibble of class |
threshold |
Numeric. The performance threshold: the minimum reporting rate (in percent) for a district to be considered compliant. Default is 90. |
region |
Optional. Filter results for a specific region (admin level 1 name). |
A tibble of class cd_district_reporting_rate.
## Not run: calculate_district_reporting_rate(data, threshold = 90) calculate_district_reporting_rate(data, threshold = 85, region = "Eastern") ## End(Not run)## Not run: calculate_district_reporting_rate(data, threshold = 90) calculate_district_reporting_rate(data, threshold = 85, region = "Eastern") ## End(Not run)
Returns a merged dataset of health coverage and system metrics at district and admin level 1 for the latest year.
calculate_health_system_comparison( .data, admin1_coverage_data, admin2_coverage_data )calculate_health_system_comparison( .data, admin1_coverage_data, admin2_coverage_data )
.data |
A |
admin1_coverage_data |
A coverage data frame at admin level 1 (with
|
admin2_coverage_data |
A coverage data frame at district level (with
|
A data frame with admin level 1 and district metrics joined side by side for comparison.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() comparison <- calculate_health_system_comparison( cache$adjusted_data, admin1_coverage_data = cache$indicator_coverage_admin1, admin2_coverage_data = cache$indicator_coverage_district ) comparison[c("adminlevel_1", "district", "ad1_ratio_fac_pop", "dis_ratio_fac_pop")]path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() comparison <- calculate_health_system_comparison( cache$adjusted_data, admin1_coverage_data = cache$indicator_coverage_admin1, admin2_coverage_data = cache$indicator_coverage_district ) comparison[c("adminlevel_1", "district", "ad1_ratio_fac_pop", "dis_ratio_fac_pop")]
Aggregates data at national, admin level 1, or district level and computes ratios and performance scores.
calculate_health_system_metrics( .data, admin_level = c("national", "adminlevel_1", "district") )calculate_health_system_metrics( .data, admin_level = c("national", "adminlevel_1", "district") )
.data |
A data frame with health system indicators and population data. |
admin_level |
One of 'national', 'adminlevel_1', or 'district'. |
A summarized data frame with calculated metrics: ratios (facility, beds, workforce, service use) and performance scores.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) national <- calculate_health_system_metrics(data, admin_level = "national") national[c("year", "ratio_fac_pop", "ratio_bed_pop", "ratio_hstaff_pop", "score_total")] regions <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") regions[c("adminlevel_1", "ratio_fac_pop", "ratio_hstaff_pop", "score_total")]path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) national <- calculate_health_system_metrics(data, admin_level = "national") national[c("year", "ratio_fac_pop", "ratio_bed_pop", "ratio_hstaff_pop", "score_total")] regions <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") regions[c("adminlevel_1", "ratio_fac_pop", "ratio_hstaff_pop", "score_total")]
calculate_indicator_coverage computes key health coverage indicators across
specified administrative levels (national, adminlevel_1, and district). The function
integrates data from multiple sources, including DHIS-2, UN estimates, ANC-1,
and Penta-1 survey data. It calculates coverage rates for a variety of vaccinations
and health metrics based on projected, survey-derived, and estimated denominators.
calculate_indicator_coverage( .data, admin_level = c("national", "adminlevel_1", "district"), derivation_population = c("totbirths_dhis2", "totlivebirths_dhis2", "totunder1_dhis2", "totpop_dhis2", "un_population", "un_births", "un_under1"), un_estimates = NULL, survey_estimates = NULL, subnational_map = NULL, anc1survey = .cd_method$denominators$anc1survey, dpt1survey = .cd_method$denominators$dpt1survey, survey_year = .cd_method$denominators$survey_year, region = NULL, show_district = TRUE, sbr = .cd_method$denominators$sbr, nmr = .cd_method$denominators$nmr, pnmr = .cd_method$denominators$pnmr, twin = .cd_method$denominators$twin, preg_loss = .cd_method$denominators$preg_loss )calculate_indicator_coverage( .data, admin_level = c("national", "adminlevel_1", "district"), derivation_population = c("totbirths_dhis2", "totlivebirths_dhis2", "totunder1_dhis2", "totpop_dhis2", "un_population", "un_births", "un_under1"), un_estimates = NULL, survey_estimates = NULL, subnational_map = NULL, anc1survey = .cd_method$denominators$anc1survey, dpt1survey = .cd_method$denominators$dpt1survey, survey_year = .cd_method$denominators$survey_year, region = NULL, show_district = TRUE, sbr = .cd_method$denominators$sbr, nmr = .cd_method$denominators$nmr, pnmr = .cd_method$denominators$pnmr, twin = .cd_method$denominators$twin, preg_loss = .cd_method$denominators$preg_loss )
.data |
A |
admin_level |
Character. Specifies the administrative level for calculations.
Options include: |
derivation_population |
Character. The population column used as the base
for the DTP1/ANC1-derived denominators ( |
un_estimates |
Optional. A tibble containing UN population estimates. Required for national-level calculations. |
survey_estimates |
Optional. A data frame of subnational survey estimates
( |
subnational_map |
Optional. A data frame mapping survey regions to
|
anc1survey |
Numeric. Survey-derived coverage rate for ANC-1 (antenatal care, first visit). Default is |
dpt1survey |
Numeric. Survey-derived coverage rate for Penta-1 (DPT1 vaccination). Default is |
survey_year |
Interger. The year of Penta-1 survey provided |
region |
Optional name of an |
show_district |
Logical. When |
sbr |
Numeric. The stillbirth rate. Default is |
nmr |
Numeric. Neonatal mortality rate. Default is |
pnmr |
Numeric. Post-neonatal mortality rate. Default is |
twin |
Numeric. Twin birth rate. Default is |
preg_loss |
Numeric. Pregnancy loss rate. Default is |
A tibble of class cd_indicator_coverage containing calculated coverage
indicators for the specified administrative level.
## Not run: # Calculate coverage indicators at the national level coverage_data <- calculate_indicator_coverage( .data = dhis2_data, admin_level = "national", un_estimates = un_data ) # Calculate coverage indicators at the district level coverage_data <- calculate_indicator_coverage( .data = dhis2_data, admin_level = "district" ) ## End(Not run)## Not run: # Calculate coverage indicators at the national level coverage_data <- calculate_indicator_coverage( .data = dhis2_data, admin_level = "national", un_estimates = un_data ) # Calculate coverage indicators at the district level coverage_data <- calculate_indicator_coverage( .data = dhis2_data, admin_level = "district" ) ## End(Not run)
calculate_inequality computes subnational health coverage metrics and evaluates
disparities compared to reference averages (either national or regional).
calculate_inequality(subnational_data, reference_data)calculate_inequality(subnational_data, reference_data)
subnational_data |
A data frame containing pre-calculated subnational health coverage data. |
reference_data |
A data frame containing pre-calculated reference health coverage data
(e.g., national data if analyzing |
A tibble (cd_inequality object) containing:
Subnational health coverage metrics.
Population shares.
MADM, MRDM, and related disparity metrics.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # regions against the national coverage inequality <- calculate_inequality( subnational_data = cache$indicator_coverage_admin1, reference_data = cache$indicator_coverage_national ) select_inequality(inequality, indicator = "instlivebirths", denominator = "dhis2")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # regions against the national coverage inequality <- calculate_inequality( subnational_data = cache$indicator_coverage_admin1, reference_data = cache$indicator_coverage_national ) select_inequality(inequality, indicator = "instlivebirths", denominator = "dhis2")
calculate_outliers_summary computes yearly percentages of non-outlier values
for each health indicator, based on precomputed 5-MAD outlier flags. Summarizes
data quality by administrative level and year.
calculate_outliers_summary( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL )calculate_outliers_summary( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL )
.data |
A |
admin_level |
Character. Aggregation level. One of:
|
region |
Optional. Restrict to a specific region (only when |
Outliers are defined using a Hampel filter with a 5-MAD threshold.
Aggregates the outlier flags by year and administrative level and computes the share of valid
(non-outlier) values per indicator. The IPD indicators are left out. Adds mean_out_all, the
average non-outlier rate across the indicators summarised.
Values are expressed as percentages (0-100).
A tibble of class cd_outlier.
## Not run: calculate_outliers_summary(data, admin_level = "district") ## End(Not run)## Not run: calculate_outliers_summary(data, admin_level = "district") ## End(Not run)
Calculates an overall quality score based on various data quality metrics. It summarizes completeness, outlier presence, and consistency of reporting in immunization health facility data.
calculate_overall_score( .data, threshold, ratio_pairs = NULL, region = NULL, labels = NULL )calculate_overall_score( .data, threshold, ratio_pairs = NULL, region = NULL, labels = NULL )
.data |
A data frame of type |
threshold |
Numeric. The performance threshold (in percent): the reporting rate and completeness a district is expected to reach. Required: it has no default. |
ratio_pairs |
Named list of indicator pairs whose ratios are scored (the default pairs when |
region |
Optional name of an |
labels |
Optional named list overriding the default row labels. May
contain |
calculate_overall_score processes multiple data quality indicators:
Completeness metrics: Percentage of expected reports, districts with complete reporting, and districts with no missing values.
Outlier metrics: Percentage of monthly values and districts without extreme outliers.
Consistency ratios: Ratios between different immunization indicators to ensure internal consistency.
The function calculates averages for the selected metrics and includes a row summarizing the annual data quality score.
A tibble with calculated scores for each metric, including a summary row for the annual quality score. The result is ordered by metric codes and ready for reporting in tabular or graphical form.
## Not run: calculate_overall_score(.data = my_data) ## End(Not run)## Not run: calculate_overall_score(.data = my_data) ## End(Not run)
Builds the same score table as calculate_overall_score(), but from
summaries that have already been calculated.
calculate_overall_score1( average_reporting_rate, district_reporting_rate, district_completeness, outliers_summary, district_outliers_summary, ratios_summary, labels = NULL, threshold = .cd_method$data_quality$reporting_threshold )calculate_overall_score1( average_reporting_rate, district_reporting_rate, district_completeness, outliers_summary, district_outliers_summary, ratios_summary, labels = NULL, threshold = .cd_method$data_quality$reporting_threshold )
average_reporting_rate |
A |
district_reporting_rate |
A |
district_completeness |
A |
outliers_summary |
A |
district_outliers_summary |
A |
ratios_summary |
A |
labels |
Optional named list overriding the default row labels, with
|
threshold |
Numeric. The performance threshold (in percent) shown in the
label of row 1b. Default is |
A tibble with calculated scores for each metric, including a summary row for the annual quality score.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) calculate_overall_score1( average_reporting_rate = calculate_average_reporting_rate(data), district_reporting_rate = calculate_district_reporting_rate(data, threshold = 90), district_completeness = calculate_district_completeness_summary(data), outliers_summary = calculate_outliers_summary(data), district_outliers_summary = calculate_district_outlier_summary(data), ratios_summary = calculate_ratios_and_adequacy(data), threshold = 90 )path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) calculate_overall_score1( average_reporting_rate = calculate_average_reporting_rate(data), district_reporting_rate = calculate_district_reporting_rate(data, threshold = 90), district_completeness = calculate_district_completeness_summary(data), outliers_summary = calculate_outliers_summary(data), district_outliers_summary = calculate_district_outlier_summary(data), ratios_summary = calculate_ratios_and_adequacy(data), threshold = 90 )
Computes ratios for specified pairs of indicators dynamically and flags whether each calculated ratio falls within an adequate range, per district and year. This function is an intermediate utility used to standardize ratio calculations and adequacy checks across indicator pairs.
calculate_ratios_and_adequacy( .data, ratio_pairs = NULL, adequate_range = .cd_method$data_quality$ratio_adequate_range, region = NULL )calculate_ratios_and_adequacy( .data, ratio_pairs = NULL, adequate_range = .cd_method$data_quality$ratio_adequate_range, region = NULL )
.data |
A data frame of type |
ratio_pairs |
A named list of indicator pairs for which ratios should be calculated.
|
adequate_range |
A numeric vector of length two specifying the inclusive
lower and upper bounds for the adequate range, typically between |
region |
Optional. Restrict analysis to one region ( |
This function standardizes ratio calculations by dynamically computing ratios and adequacy flags for specified pairs of indicators. It operates in three main stages:
Summing Indicators: Calculates the sum of each indicator by district
and year.
Calculating Ratios: Divides the summed numerator by the summed
denominator for each pair in ratio_pairs, creating a column for each ratio.
Checking Adequacy: Flags each ratio as adequate if it falls within the
specified adequate_range, returning 1 for adequate and 0 otherwise.
A data frame with columns for:
Summed indicators by district and year: Summed values for each indicator
across districts within the specified year, based on input in ratio_pairs.
Ratios: Each ratio is calculated as the sum of the specified numerator divided by the sum of the specified denominator for each pair.
Adequacy flags: For each ratio, an adequacy flag (e.g., adeq_ratioAP)
is generated, set to 1 if the ratio falls within the adequate_range,
and 0 otherwise.
The output is aggregated by year and includes means of ratios and adequacy flags.
calculate_ratios_summary() and calculate_district_ratios_summary(), which summarise the result.
## Not run: # Calculate ratios and adequacy checks using custom ranges calculate_ratios_and_adequacy(data, ratio_pairs = list( "ratioAP" = c("anc1", "penta1"), "ratioPP" = c("penta1", "penta3") ), adequate_range = c(1, 1.5) ) ## End(Not run)## Not run: # Calculate ratios and adequacy checks using custom ranges calculate_ratios_and_adequacy(data, ratio_pairs = list( "ratioAP" = c("anc1", "penta1"), "ratioPP" = c("penta1", "penta3") ), adequate_range = c(1, 1.5) ) ## End(Not run)
Computes yearly summaries for specified indicator ratios, assessing trends across years and providing both actual and expected ratios for each indicator. It evaluates specified indicator pairs to calculate ratios and compares actual values with expected ratios, based on predefined survey coverage values. The summary facilitates monitoring consistency of key health indicators over time.
calculate_ratios_summary( .data, survey_coverage = .cd_method$data_quality$ratio_expected_coverage, anc1_penta1_mortality = .cd_method$data_quality$ratio_anc1_penta1_mortality )calculate_ratios_summary( .data, survey_coverage = .cd_method$data_quality$ratio_expected_coverage, anc1_penta1_mortality = .cd_method$data_quality$ratio_anc1_penta1_mortality )
.data |
A data frame containing yearly data for specified indicators.
Expected columns include |
survey_coverage |
A named vector of assumed coverage rates for each indicator.
Default is |
anc1_penta1_mortality |
A numeric multiplier applied specifically to the |
The function provides insights into indicator relationships over time and evaluates
deviations from expected values. It enables data quality checks and trend analysis
by summarizing ratios yearly and including expected values for comparison. The "Expected Ratio"
row incorporates predefined survey coverage and serves as a reference for assessing
the adequacy of each indicator's ratio.
A cd_ratios_summary object, a data frame containing:
year: Year of each calculated ratio, with an additional row "Expected Ratio"
to represent expected values for each indicator ratio based on survey_coverage.
Indicator Ratios: Columns for each ratio, showing actual yearly values
and an expected value row based on survey_coverage.
Additional Columns: Health indicator values for each year.
## Not run: # Basic usage with default parameters calculate_ratios_summary(cd_data) # Custom survey coverage and mortality adjustments for "ratioAP" calculate_ratios_summary(cd_data, survey_coverage = c(anc1 = 0.95, penta1 = 0.92, penta3 = 0.85), anc1_penta1_mortality = 1.05 ) ## End(Not run)## Not run: # Basic usage with default parameters calculate_ratios_summary(cd_data) # Custom survey coverage and mortality adjustments for "ratioAP" calculate_ratios_summary(cd_data, survey_coverage = c(anc1 = 0.95, penta1 = 0.92, penta3 = 0.85), anc1_penta1_mortality = 1.05 ) ## End(Not run)
A card with one chart of the ratios between related indicators (ANC1 to Penta1, OPV1 to OPV3 and
Penta1 to Penta3 have translated labels). It is the first card of the Internal consistency page
(internal_consistency_ui()) and has no filters. It reads ratios_summary from the dataset.
calculate_ratios_ui(id, i18n) calculate_ratios_server(id, cache, i18n, active = reactive(TRUE))calculate_ratios_ui(id, i18n) calculate_ratios_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
calculate_ratios_ui() returns the card's UI as Shiny tags. calculate_ratios_server()
is called for its side effects.
## Not run: # the card in a page module, as the Internal consistency page uses it my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, calculate_ratios_ui(ns("ratios"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { calculate_ratios_server("ratios", cache, i18n, active = active) }) } ## End(Not run)## Not run: # the card in a page module, as the Internal consistency page uses it my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, calculate_ratios_ui(ns("ratios"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { calculate_ratios_server("ratios", cache, i18n, active = active) }) } ## End(Not run)
Evaluates administrative regions to determine the percentage that meet specific coverage targets or fall below specific dropout thresholds for a given year.
calculate_threshold( .data, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), indicator = c("anc4", "instlivebirths", "vaccine", "dropout") )calculate_threshold( .data, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), indicator = c("anc4", "instlivebirths", "vaccine", "dropout") )
.data |
A tibble of class |
denominator |
Character. The denominator used (e.g., |
indicator |
Character. The health indicator group to evaluate ( |
A cd_threshold object summarizing the percentage of regions meeting the criteria by year.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$indicator_coverage_admin1 # the percentage of regions that reach the target for institutional live births, by year calculate_threshold(coverage, denominator = "dhis2", indicator = "instlivebirths") # for the three tracer vaccines, with the penta1 denominator calculate_threshold(coverage, denominator = "penta1", indicator = "vaccine")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$indicator_coverage_admin1 # the percentage of regions that reach the target for institutional live births, by year calculate_threshold(coverage, denominator = "dhis2", indicator = "instlivebirths") # for the three tracer vaccines, with the penta1 denominator calculate_threshold(coverage, denominator = "penta1", indicator = "vaccine")
The admin levels a page can be shown at, in the form a filter chip takes them.
cd_admin_level_ui() builds its level chip from this, and a page can use it to offer the same
levels in a control of its own.
cd_admin_level_choices(include_national = FALSE)cd_admin_level_choices(include_national = FALSE)
include_national |
Logical. |
A named character vector. The values are the levels ("national" when asked for,
"adminlevel_1", "district") and the names are the translation keys of their labels.
cd_admin_level_choices() cd_admin_level_choices(include_national = TRUE)cd_admin_level_choices() cd_admin_level_choices(include_national = TRUE)
Two filter chips for a page's filter bar: one chooses the admin level (admin level 1 or district,
and national when asked for), the other a single area at that level. A page puts
cd_admin_level_ui() in its filter bar, calls cd_admin_level_server() in its server, and reads
the chosen level and area from the reactive the server returns. cd_admin_parts() splits that
reactive into one reactive for the level and one for the area.
cd_admin_level_ui(id, i18n, include_national = FALSE, show_admin_level = TRUE) cd_admin_level_server( id, cache, i18n, allow_select_all = FALSE, show_district = TRUE, show_region = TRUE, show_admin_level = TRUE, selected_admin1 = reactive(NULL) )cd_admin_level_ui(id, i18n, include_national = FALSE, show_admin_level = TRUE) cd_admin_level_server( id, cache, i18n, allow_select_all = FALSE, show_district = TRUE, show_region = TRUE, show_admin_level = TRUE, selected_admin1 = reactive(NULL) )
id |
The module's id. |
i18n |
The app's translator (a |
include_national |
Logical. |
show_admin_level |
Logical. |
cache |
A reactive that returns the dataset, a CacheConnection. |
allow_select_all |
Logical. |
show_district |
Logical. Whether an area can be chosen at the district level. With a level
chip, |
show_region |
Logical. |
selected_admin1 |
A reactive that returns the name of an admin level 1 area, or |
The region chip is drawn by the server, so it appears only where there are areas to
choose from: never at the national level, never when show_region is FALSE, and at the
district level only when show_district is TRUE. Its options are the areas of
cache()$subnational_regions at the chosen level, and districts are listed under the admin level
1 area they belong to. Changing the level draws a new region chip, so an area of the old level is
never kept. The list of areas is debounced by 300 milliseconds.
With allow_select_all = TRUE the region chip starts on an "all" option, which the server
reports as a NULL region. Without it the chip starts on the first area in the list.
When show_admin_level is FALSE there is no level chip, and the level is fixed: "district"
when show_district is TRUE (the default), "adminlevel_1" otherwise. Give show_admin_level
the same value in the ui and the server call.
cd_admin_level_ui() returns the UI as Shiny tags: the level chip (when shown) and the
place where the server draws the region chip.
cd_admin_level_server() returns a reactive holding a list with two elements:
admin_level: "national", "adminlevel_1" or "district".
region: the name of the chosen area, or NULL when the region chip is not shown or "all"
is chosen.
While the region chip is shown but has not yet reported a value, the reactive stops quietly (as
shiny::req() does), so what depends on it waits.
## Not run: # in a page's ui cd_filter_bar(cd_admin_level_ui(ns("admin_level"), i18n)) # in the page's server admin <- cd_admin_level_server("admin_level", cache, i18n, allow_select_all = TRUE) observe({ admin()$admin_level admin()$region }) ## End(Not run)## Not run: # in a page's ui cd_filter_bar(cd_admin_level_ui(ns("admin_level"), i18n)) # in the page's server admin <- cd_admin_level_server("admin_level", cache, i18n, allow_select_all = TRUE) observe({ admin()$admin_level admin()$region }) ## End(Not run)
cd_admin_level_server() returns one reactive holding both the admin level and the region. Pages
usually hand the two to their charts and tables as separate reactives, and this gives one
reactive for each.
cd_admin_parts(admin)cd_admin_parts(admin)
admin |
The reactive |
A list of two reactives:
admin_level: the chosen admin level.
region: the chosen area's name, or NULL when the region chip is not shown or "all" is
chosen.
Both wait (as shiny::req() does) until admin() has a value.
## Not run: admin <- cd_admin_level_server("admin_level", cache, i18n) parts <- cd_admin_parts(admin) parts$admin_level() parts$region() ## End(Not run)## Not run: admin <- cd_admin_level_server("admin_level", cache, i18n) parts <- cd_admin_parts(admin) parts$admin_level() parts$region() ## End(Not run)
Puts a whole Countdown app together and returns it as a Shiny app: the frame every app shares
(header, sidebar, language picker), the Introduction and Load Data screens, and the app's own
pages. An app's run_app() sets its options, builds its translator, lists its pages and its nav
tree, and then calls cd_app(). See cd2030.rmncah::run_app() for a complete one.
cd_app( app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, upload_ui = get0("upload_data_ui", envir = parent.frame()) %||% cd_upload_data_ui, upload_server = get0("upload_data_server", envir = parent.frame()) %||% cd_upload_data_server )cd_app( app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, upload_ui = get0("upload_data_ui", envir = parent.frame()) %||% cd_upload_data_ui, upload_server = get0("upload_data_server", envir = parent.frame()) %||% cd_upload_data_server )
app_name |
The app's name, shown in the header. |
app_version |
The app's version, shown in the header. |
theme |
The app's colour theme: |
nav_sections |
The sidebar's nav tree: a list of nav sections, made with |
registry |
The app's pages: a list of page definitions made with the kit's |
i18n |
The app's translator (a |
language |
The language the app starts in, for example |
selected_file |
The path of a dataset to open when the app starts, or |
upload_ui |
The ui function of the Load Data screen, called as
|
upload_server |
The server function of the Load Data screen, called as
|
cd_app() calls the kit's datasuite.ui::app_frame() and adds what is the same in
every Countdown app:
The Introduction screen and the Load Data screen. The app opens on Load Data, and these two screens are never locked.
The dataset. It is the reactive the Load Data screen returns, and every page receives it as
cache. The pages unlock once the dataset holds Countdown data. The nav items marked
requires_adjustment = TRUE unlock once the data is also adjusted.
The row naming the denominators in use, in every page header (cd_denominator_header()).
The language. A dataset that has just been uploaded takes the language on screen, and a dataset that is opened again shows the language it was saved with.
The reports' colours, which follow theme.
What DataSuite's chat can read and do in the app: the filters of the page on show, the dataset, and actions that set filters and save, read, change and write reports.
Before calling it, the app registers its translator with cd_use_i18n() and its pages with
cd_use_pages().
A Shiny app object. Printing it, or passing it to shiny::runApp(), runs the app.
## Not run: i18n <- shiny.i18n::init_i18n(translation_json_path = cd_translations("translation.json")) cd_use_i18n(i18n) pages <- my_pages() cd_use_pages(pages) cd_app( app_name = "My Countdown app", app_version = "1.0.0", theme = "vaccine", nav_sections = list(cd_nav_start(), cd_nav_quality(), cd_nav_denominators()), registry = pages, i18n = i18n, language = "en", selected_file = NA ) ## End(Not run)## Not run: i18n <- shiny.i18n::init_i18n(translation_json_path = cd_translations("translation.json")) cd_use_i18n(i18n) pages <- my_pages() cd_use_pages(pages) cd_app( app_name = "My Countdown app", app_version = "1.0.0", theme = "vaccine", nav_sections = list(cd_nav_start(), cd_nav_quality(), cd_nav_denominators()), registry = pages, i18n = i18n, language = "en", selected_file = NA ) ## End(Not run)
Hands one fit to a future worker and returns at once. The worker runs generate_bayes_model()
on the coverage data, overall score, indicator and denominator in inputs, with cd2030.core
attached and a parallel-safe random seed. The Bayesian page uses this function as the task of its
shiny::ExtendedTask. With the default sequential plan the fit runs in the calling process;
see cd_start_bayes_workers().
cd_bayes_fit_task(inputs)cd_bayes_fit_task(inputs)
inputs |
A list with |
A promise of a list with two elements: key, which is inputs$key unchanged, and
model, the fitted model. The key lets the caller keep the model for the request it was fitted
for.
## Not run: cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # one fit, kept in the dataset when it ends (it takes minutes) inputs <- cache$bayes_model_inputs("national", "penta3") promises::then(cd_bayes_fit_task(inputs), function(out) cache$keep_bayes_model(out$key, out$model)) # in a Shiny server: the task of an ExtendedTask fit <- ExtendedTask$new(cd_bayes_fit_task) fit$invoke(inputs) ## End(Not run)## Not run: cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # one fit, kept in the dataset when it ends (it takes minutes) inputs <- cache$bayes_model_inputs("national", "penta3") promises::then(cd_bayes_fit_task(inputs), function(out) cache$keep_bayes_model(out$key, out$model)) # in a Shiny server: the task of an ExtendedTask fit <- ExtendedTask$new(cd_bayes_fit_task) fit$invoke(inputs) ## End(Not run)
The indicators the Bayesian coverage model has a survey series for. They are the default tabs of
the Bayesian page (bayesian_ui()). An app shows only the ones its data has by setting
bayes_indicators in options(cd2030.config = ), which the page reads with
cd_cfg("bayes_indicators") (the vaccine app: penta3 and measles1).
cd_bayes_indicatorscd_bayes_indicators
A character vector of five indicator names: "anc4", "anc_1trimester", "ideliv",
"measles1" and "penta3".
cd_bayes_indicators # the tabs an app shows: its own setting, or these cd_cfg("bayes_indicators", cd_bayes_indicators)cd_bayes_indicators # the tabs an app shows: its own setting, or these cd_cfg("bayes_indicators", cd_bayes_indicators)
For R outside DataSuite.
cd_bayes_install_command(packages = cd_bayes_packages_missing())cd_bayes_install_command(packages = cd_bayes_packages_missing())
packages |
The packages to install, by default the missing ones. |
The command, as a string.
cd_bayes_install_command(c("bayescoveragemodel", "bayescoveragedeploy")) # only what is missing missing <- cd_bayes_packages_missing() if (length(missing) > 0) cd_bayes_install_command(missing)cd_bayes_install_command(c("bayescoveragemodel", "bayescoveragedeploy")) # only what is missing missing <- cd_bayes_packages_missing() if (length(missing) > 0) cd_bayes_install_command(missing)
Checks without loading them (loading brings in Stan).
cd_bayes_packages_missing()cd_bayes_packages_missing()
A character vector: the packages generate_bayes_model() needs and that are not installed, empty when
the model can run.
cd_bayes_packages_missing() if (length(cd_bayes_packages_missing()) == 0) { message("The Bayesian model can run.") }cd_bayes_packages_missing() if (length(cd_bayes_packages_missing()) == 0) { message("The Bayesian model can run.") }
The shared pages are the same in every Countdown app, and what differs between apps is kept in
one list of settings. An app sets the list once, in its run_app(), with
options(cd2030.config = list(...)), and the pages read the setting they need with cd_cfg().
This way an app (RMNCAH, vaccine, or one for a custom indicator group) says what is particular to
it, and no shared page depends on a group's name.
cd_cfg(key, default = NULL)cd_cfg(key, default = NULL)
key |
The setting's name, a string. |
default |
What to return when the app has not set |
A setting may be a value or a function with no arguments that returns one. A function is called each time the setting is read, so its answer can follow something that is only known later, such as the indicator group.
The settings the shared pages read (each page gives its own default):
nat_cov_indicators: the tabs of the national and sub-national coverage pages. It may include
"fpet", which adds the family planning chart.
bayes_indicators: the tabs of the Bayesian coverage model pages.
target_indicators: the tabs of the coverage target pages.
equity_indicators: the tabs of the Equity Assessment page. equity_custom_exclude: the
indicators its Custom tab leaves out.
cov_trend_indicators, sub_derived_indicators, survey_comp_indicators: the tabs of the
three cards of the Denominator Selection page.
adjustment_indicators: the tabs of the Data Adjustment Changes page.
k_factors: the adjustment factors, as list(name = list(id, label)).
reporting_rate_indicators, reporting_rate_facet_ncol: the Reporting Rate page's service
chips and the number of columns of its national chart.
consistency_pairs: a list of c(x, y) pairs of indicators, one tab of the Consistency Checks
card each.
has_maternal: whether the indicator group has a maternal denominator (see
cd_has_maternal()).
The setting's value. When the setting is a function, the value that function returns.
When the setting is not set, default.
old <- options(cd2030.config = list( target_indicators = c("penta3", "measles1"), equity_indicators = function() c("anc4", "penta3") )) cd_cfg("target_indicators") cd_cfg("equity_indicators") cd_cfg("consistency_pairs", default = list()) options(old)old <- options(cd2030.config = list( target_indicators = c("penta3", "measles1"), equity_indicators = function() c("anc4", "penta3") )) cd_cfg("target_indicators") cd_cfg("equity_indicators") cd_cfg("consistency_pairs", default = list()) options(old)
A table of every chart with options saved in a dataset's cache: which chart (its cd_chart_id(), or for the screen the
chart's place in the app), whether they are for the screen or for reports, how many options are set, and the group it
belongs to (the first two parts of its id, e.g. coverage_filtered.national). Use it to see which chart ids a report will
pick options up for.
cd_chart_catalog(cache)cd_chart_catalog(cache)
cache |
A tibble with id, target ("screen", "report" or "dataset"), group, n_options and options (a
one-line summary).
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_chart_options("default", cd_chart_options(legend_position = "bottom")) cache$set_chart_options( "report/coverage_filtered.national.penta3", cd_chart_options(title = "Penta3 coverage") ) cd_chart_catalog(cache)cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_chart_options("default", cd_chart_options(legend_position = "bottom")) cache$set_chart_options( "report/coverage_filtered.national.penta3", cd_chart_options(title = "Penta3 coverage") ) cd_chart_catalog(cache)
A stable, readable name for the chart a plot draws, made from the data it is drawn from: the kind of data, the admin level
and the indicator ("coverage_filtered.national.anc4"). The app's customize panel and the reports build it the same way, so
options saved for a chart in the app ("report/<id>") reach the same chart in a generated report. Ids are grouped by their
parts: everything under coverage_filtered.national is the national coverage charts.
cd_chart_id(x)cd_chart_id(x)
x |
The data a plot method was given. |
A string, or NULL when the data does not say what it is.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cd_chart_id(calculate_average_reporting_rate(data)) # plain data does not say what it is cd_chart_id(mtcars)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cd_chart_id(calculate_average_reporting_rate(data)) # plain data does not say what it is cd_chart_id(mtcars)
Members that return a table: the precomputed results (active bindings such as reporting_rate_district) and the
methods that compute one (calculate_coverage(), get_filtered_coverage(), decompose_change()...). Raw data
(countdown_data, adjusted_data) and settings are left out.
cd_chartable_members()cd_chartable_members()
A character vector of member names.
head(cd_chartable_members())head(cd_chartable_members())
One chart with the tools every Countdown chart has: a panel to customize how it looks, a download
of the chart as a picture, and a download of its data as an Excel workbook. The page gives the
data and says how to draw it, and this module does the rest. It is the chart that goes in the
tabs of cd_tabbed_charts_ui(), and it works as well on its own in a card.
cd_coverage_plot_ui(id, toolbar_inline = FALSE) cd_coverage_plot_toolbar_ui(id) cd_coverage_plot_server( id, filename, data_fn, ..., sheet_name, i18n, plot_fun = NULL, about = NULL )cd_coverage_plot_ui(id, toolbar_inline = FALSE) cd_coverage_plot_toolbar_ui(id) cd_coverage_plot_server( id, filename, data_fn, ..., sheet_name, i18n, plot_fun = NULL, about = NULL )
id |
The module's id. |
toolbar_inline |
Logical. |
filename |
A reactive that returns the first part of the downloaded files' name. The date and time and the extension are added to it. |
data_fn |
A reactive that returns the data the chart draws. It is also what the Excel download holds. |
... |
Arguments for |
sheet_name |
A reactive that returns the name of the sheet in the Excel download. It comes
after |
i18n |
The app's translator (a |
plot_fun |
A function |
about |
What the chart is, for the app's AI: |
The chart is drawn with plot_fun(data_fn()) once data_fn() has a value. When
plot_fun is NULL it is drawn with plot(data_fn(), ...), so the data must then have a
plot() method.
The Excel download holds data_fn() on one sheet named sheet_name(). The picture is the chart
as it is on screen, as a PNG file. Both files are named filename() followed by the date and
time.
In an app made with cd_app(), what the reader changes in the customize panel is kept in the
dataset. The chart is also registered with the app's AI bridge, which can then list it and read
its data.
By default the tools sit over a corner of the chart. With toolbar_inline = TRUE,
cd_coverage_plot_ui() leaves them out, and the page puts them somewhere else (a card's header,
for example) with cd_coverage_plot_toolbar_ui(), called with the same id.
cd_coverage_plot_ui() returns the UI as Shiny tags: the chart, with its tools unless
toolbar_inline is TRUE.
cd_coverage_plot_toolbar_ui() returns the chart's tools alone, as Shiny tags.
cd_coverage_plot_server() returns nothing useful. It is called for what it does.
## Not run: # in a page's ui cd_coverage_plot_ui(ns("coverage")) # in the page's server cd_coverage_plot_server("coverage", filename = reactive("penta3_coverage"), data_fn = reactive(my_coverage_data(cache())), sheet_name = reactive(i18n$t("opt_penta3")), i18n = i18n, plot_fun = function(d) plot(d, title = "Penta3 coverage") ) ## End(Not run)## Not run: # in a page's ui cd_coverage_plot_ui(ns("coverage")) # in the page's server cd_coverage_plot_server("coverage", filename = reactive("penta3_coverage"), data_fn = reactive(my_coverage_data(cache())), sheet_name = reactive(i18n$t("opt_penta3")), i18n = i18n, plot_fun = function(d) plot(d, title = "Penta3 coverage") ) ## End(Not run)
Checks a custom chart description, reads the data of the dataset member it names and applies the transforms it lists. The result is the table the chart is drawn from.
cd_custom_chart_data(cache, spec)cd_custom_chart_data(cache, spec)
cache |
A |
spec |
A custom chart description (report kind |
The data frame after the spec's transforms.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) spec <- list( title = "Antenatal care reporting rate by region, 2023", data = list(member = "reporting_rate_admin1"), transform = list( list(filter = list(year = 2023)), list(select = c("adminlevel_1", "anc_rr")) ), plot = list(geom = "col", x = "adminlevel_1", y = "anc_rr") ) cd_custom_chart_data(cache, spec)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) spec <- list( title = "Antenatal care reporting rate by region, 2023", data = list(member = "reporting_rate_admin1"), transform = list( list(filter = list(year = 2023)), list(select = c("adminlevel_1", "anc_rr")) ), plot = list(geom = "col", x = "adminlevel_1", y = "anc_rr") ) cd_custom_chart_data(cache, spec)
The indicators a tabbed chart card (cd_tabbed_charts_ui()) gives a tab each when the page names
none.
cd_default_indicator_set()cd_default_indicator_set()
Reads options(cd2030.default_indicators = ). An app sets it to a character vector of
indicator codes, or to a function with no arguments that returns one. A function is called each
time, so its answer can follow something that is only known later, such as the indicator group.
When the option is not set, the result is cd_default_indicators.
A character vector of indicator codes.
cd_default_indicator_set() old <- options(cd2030.default_indicators = function() c("penta3", "measles1")) cd_default_indicator_set() options(old)cd_default_indicator_set() old <- options(cd2030.default_indicators = function() c("penta3", "measles1")) cd_default_indicator_set() options(old)
The indicators a tabbed chart card (cd_tabbed_charts_ui()) gives a tab each when the page names
none and the app has not set its own. This is the RMNCAH app's set. Read the indicators in use
with cd_default_indicator_set(), which also takes the app's option into account.
cd_default_indicatorscd_default_indicators
A character vector of five indicator codes: "anc4", "instlivebirths",
"low_bweight", "penta3" and "measles1".
cd_default_indicatorscd_default_indicators
The translation keys of the label and of the hint a denominator chip shows. cd_denominator_ui()
uses them, and a page that draws a denominator chip of its own can use them to match it.
cd_denominator_chip_keys(is_maternal)cd_denominator_chip_keys(is_maternal)
is_maternal |
Logical. |
A list of two translation keys, label and hint.
cd_denominator_chip_keys(is_maternal = TRUE) cd_denominator_chip_keys(is_maternal = FALSE)cd_denominator_chip_keys(is_maternal = TRUE) cd_denominator_chip_keys(is_maternal = FALSE)
Every denominator the denominator chip can offer, in the form a filter chip takes them. This is
the full set, which the RMNCAH app uses. An app with fewer denominators sets its own (see
cd_denominator_options()).
cd_denominator_choicescd_denominator_choices
A named character vector of length 5. The values are the denominator ids and the names are the translation keys of their labels:
"dhis2": the DHIS2 population projection.
"anc1" and "penta1": the denominators derived from ANC1 and from Penta1.
"penta1derived" and "anc1derived": the growth-projected denominators (Penta1 and ANC1
population growth).
cd_denominator_choicescd_denominator_choices
What a Countdown app adds to the server of every page header: it fills the header's denominator
output with cd_denominator_row() for the denominators the dataset uses. cd_app() passes it to
the app frame (app_frame(page_header_extra = )), which runs it inside each page header's
module, so a page never calls it itself.
cd_denominator_header(input, output, session, cache, i18n)cd_denominator_header(input, output, session, cache, i18n)
input, output, session
|
The |
cache |
A reactive that returns the dataset, a CacheConnection. |
i18n |
The app's translator (a |
It reads cache()$denominator and, when the app has a maternal denominator
(cd_has_maternal()), cache()$maternal_denominator. The row is drawn once the values it needs
are set, and again when one of them changes.
Nothing useful. It is called for what it does.
## Not run: # cd_app() gives it to the app frame, which calls it in each page header's module app_frame(app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, data_server = data_server, page_header_extra = cd_denominator_header ) # the call the frame makes, where the header has uiOutput(ns("denominator")) moduleServer("header", function(input, output, session) { cd_denominator_header(input, output, session, cache = cache, i18n = i18n) }) ## End(Not run)## Not run: # cd_app() gives it to the app frame, which calls it in each page header's module app_frame(app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, data_server = data_server, page_header_extra = cd_denominator_header ) # the call the frame makes, where the header has uiOutput(ns("denominator")) moduleServer("header", function(input, output, session) { cd_denominator_header(input, output, session, cache = cache, i18n = i18n) }) ## End(Not run)
Gives the display label of each denominator option, keyed by its id. With a translator the labels are translated; a label that has no translation stays in English.
cd_denominator_labels(i18n = NULL, ids = .cd_dict_denominators$id)cd_denominator_labels(i18n = NULL, ids = .cd_dict_denominators$id)
i18n |
Optional translator ( |
ids |
Which denominators, in this order. Default: all six. |
A named character vector, id -> label.
cd_denominator_labels()cd_denominator_labels()
The choices the denominator chip shows in the running app. Use it wherever a page must list or check the app's denominators, so that a page shared between apps never shows one the app does not have.
cd_denominator_options()cd_denominator_options()
Reads options(cd2030.denominator_choices = ). An app whose indicator group has fewer
denominators sets that option to its own named vector (the vaccine app leaves out
"anc1derived"). When the option is not set, the result is cd_denominator_choices.
A named character vector: the values are the denominator ids and the names are the translation keys of their labels.
cd_denominator_options() old <- options(cd2030.denominator_choices = c("lbl_denom_dhis2_proj" = "dhis2")) cd_denominator_options() options(old)cd_denominator_options() old <- options(cd2030.denominator_choices = c("lbl_denom_dhis2_proj" = "dhis2")) cd_denominator_options() options(old)
The row a Countdown page header shows under its title: a label, one chip naming the vaccination
denominator, one naming the maternal denominator when there is one, and a note saying where the
denominators are set. cd_denominator_header() draws it on every page. Call it directly to show
the same row somewhere else.
cd_denominator_row(vaccination, maternal = NULL, i18n)cd_denominator_row(vaccination, maternal = NULL, i18n)
vaccination |
The id of the vaccination denominator in use, for example |
maternal |
The id of the maternal denominator in use, shown the same way. |
i18n |
The app's translator (a |
The UI as Shiny tags (a div).
## Not run: cd_denominator_row("penta1", "anc1", i18n) cd_denominator_row("penta1", i18n = i18n) ## End(Not run)## Not run: cd_denominator_row("penta1", "anc1", i18n) cd_denominator_row("penta1", i18n = i18n) ## End(Not run)
A filter chip that chooses the denominator the dataset uses, either the vaccination denominator or the maternal one. The choice is kept in the dataset, so every page that reads the denominator follows it. The Denominator Selection page uses one chip for each.
cd_denominator_ui(id, i18n, allow_input = FALSE, is_maternal = FALSE) cd_denominator_server( id, cache, i18n, label = "title_denom_select_best", allowInput = FALSE, is_maternal = FALSE, display_mode = "combined" )cd_denominator_ui(id, i18n, allow_input = FALSE, is_maternal = FALSE) cd_denominator_server( id, cache, i18n, label = "title_denom_select_best", allowInput = FALSE, is_maternal = FALSE, display_mode = "combined" )
id |
The module's id. |
i18n |
The app's translator (a |
allow_input |
Logical. |
is_maternal |
Logical. |
cache |
A reactive that returns the dataset, a CacheConnection. |
label |
Not used. |
allowInput |
Logical. |
display_mode |
Not used. |
The chip starts empty and the server fills it from the dataset once the chip is on the
page: cache()$denominator, or cache()$maternal_denominator when is_maternal is TRUE. When
the value changes in the dataset, the chip follows. When the reader chooses a denominator, the
server saves it with the dataset's set_denominator() or set_maternal_denominator(). An empty
chip saves nothing.
The chip is drawn, and the dataset kept in step, only when asked for: pass allow_input = TRUE
to the ui and allowInput = TRUE to the server (the two arguments are spelled differently). With
the defaults the ui is NULL and the server does nothing.
The chip's choices are cd_denominator_options().
cd_denominator_ui() returns the UI as Shiny tags (the chip), or NULL when
allow_input is FALSE.
cd_denominator_server() returns nothing useful. It is called for what it does.
## Not run: # in a page's ui cd_denominator_ui(ns("vaxx_denominator"), i18n, allow_input = TRUE) # in the page's server cd_denominator_server("vaxx_denominator", cache, i18n, allowInput = TRUE) ## End(Not run)## Not run: # in a page's ui cd_denominator_ui(ns("vaxx_denominator"), i18n, allow_input = TRUE) # in the page's server cd_denominator_server("vaxx_denominator", cache, i18n, allowInput = TRUE) ## End(Not run)
Splits each name into its parts (cd_dictionary()) and says in plain words what the column holds – e.g.
cov_penta3_penta1derived: "Coverage of Pentavalent 3 (%), denominator: Penta1 population growth". A name it
cannot read gets type "unknown" and no description: it never guesses.
cd_describe_columns(names)cd_describe_columns(names)
names |
Column names. |
A data frame, one row per name: column, type (count, coverage, population, population_growth,
survey, survey_upper, survey_lower, reporting_rate, fixed, unknown), indicator, denominator,
population (the parts' ids, or NA) and description.
cd_describe_columns(c("cov_penta3_penta1derived", "totinftpenta_anc1", "r_penta1", "vacc_rr", "year", "xyz"))cd_describe_columns(c("cov_penta3_penta1derived", "totinftpenta_anc1", "r_penta1", "vacc_rr", "year", "xyz"))
The package names its data from a few parts: an indicator (penta1), a denominator option (anc1derived), a
target population (totinftpenta) and prefixes such as cov_ (coverage) or r_ (survey estimate). This is what
each part means, and how they combine. Read meanings from here, not from the spelling: anc1 and penta1 are the
ANC1-derived and Penta1-derived denominators, while anc1derived and penta1derived are the population
growth ones.
cd_dictionary()cd_dictionary()
A list of data frames: denominators (id, label, meaning, levels, key – the label's translation key),
indicators (id, label, group, computed), populations (id, label, meaning, unit), reporting_rates (id,
meaning), columns (fixed column names: id, meaning) and grammar (pattern, meaning, example).
cd_describe_columns() to read column names with it.
cd_dictionary()$denominators[, c("id", "label")]cd_dictionary()$denominators[, c("id", "label")]
The last step of every plot method: resolve_chart_options() then apply_chart_options(). While a report renders
(export_report()) the report's saved options sit underneath: the dataset-wide ones, then those saved for this type of
graph (cd_chart_type()), then those saved for this very chart (cd_chart_id()); what the plot method or the template
passes wins over all of them.
cd_finish_plot(p, options = NULL, ..., .source = NULL)cd_finish_plot(p, options = NULL, ..., .source = NULL)
p |
A ggplot. |
options, ...
|
|
.source |
The data the plot was made from; its |
The ggplot with the options applied.
p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() cd_finish_plot(p, title = "Weight and fuel use", x_title = "Weight", y_title = "Miles per gallon") # the same as one options object, the way a plot method receives it cd_finish_plot(p, cd_chart_options(title = "Weight and fuel use", legend_position = "bottom"))p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() cd_finish_plot(p, title = "Weight and fuel use", x_title = "Weight", y_title = "Miles per gallon") # the same as one options object, the way a plot method receives it cd_finish_plot(p, cd_chart_options(title = "Weight and fuel use", legend_position = "bottom"))
Tells a shared page whether to show what belongs to the maternal denominator: its chip on the Denominator Selection page and its entry in the page header's denominator row.
cd_has_maternal()cd_has_maternal()
The answer is the app's has_maternal setting (see cd_cfg()). When the app does not
set it, the answer is TRUE unless getOption("cd2030.selected_group") is "vaccine".
TRUE or FALSE.
old <- options(cd2030.config = list(has_maternal = FALSE)) cd_has_maternal() options(old)old <- options(cd2030.config = list(has_maternal = FALSE)) cd_has_maternal() options(old)
Gives the display label of each indicator, keyed by its code (anc1 -> "ANC 1"). Charts use
it to name indicators on an axis, in place of the column names. With a translator the labels
are translated (the key of an indicator is opt_<code>); a label that has no translation
stays in English, and a code the package does not know is returned as it is.
cd_indicator_labels(i18n = NULL, indicators = names(.cd_dict_indicator_labels))cd_indicator_labels(i18n = NULL, indicators = names(.cd_dict_indicator_labels))
i18n |
Optional translator ( |
indicators |
Which indicators, in this order. Default: every indicator the package knows. |
A named character vector, code -> label.
cd_indicator_labels(indicators = c("anc1", "penta3", "instlivebirths"))cd_indicator_labels(indicators = c("anc1", "penta3", "instlivebirths"))
A filter chip that chooses one indicator. A page puts cd_indicator_ui() in its filter bar or in
a card, calls cd_indicator_server() in its server, and reads the chosen indicator from the
reactive the server returns. The chip starts on its first choice.
cd_indicator_ui( id, i18n, label = NULL, tooltip = NULL, indicators = NULL, select_all = FALSE ) cd_indicator_server(id)cd_indicator_ui( id, i18n, label = NULL, tooltip = NULL, indicators = NULL, select_all = FALSE ) cd_indicator_server(id)
id |
The module's id. |
i18n |
The app's translator (a |
label |
The translation key of the chip's label. |
tooltip |
The translation key of a hint shown with the chip, or |
indicators |
A character vector of indicator codes, the chip's choices. Without names, each
indicator's label is the translation of |
select_all |
Logical. |
cd_indicator_ui() returns the UI as Shiny tags (the chip).
cd_indicator_server() returns a reactive holding the chosen indicator's code as a string. It
holds "" when "all" is chosen, and NULL until the chip has reported its first value.
## Not run: # in a page's ui cd_indicator_ui(ns("indicator"), i18n, indicators = c("penta3", "measles1"), select_all = TRUE) # in the page's server indicator <- cd_indicator_server("indicator") observe(print(indicator())) ## End(Not run)## Not run: # in a page's ui cd_indicator_ui(ns("indicator"), i18n, indicators = c("penta3", "measles1"), select_all = TRUE) # in the page's server indicator <- cd_indicator_server("indicator") observe(print(indicator())) ## End(Not run)
Reads an active binding, or calls a method with args (arguments it doesn't take are left out), and returns the
result as a plain data frame (a map's geometry dropped).
cd_member_data(cache, member, args = list())cd_member_data(cache, member, args = list())
cache |
A |
member |
A member name, one of |
args |
A named list of arguments for a method. |
A data frame.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # a precomputed result cd_member_data(cache, "reporting_rate_national") # a method, with its arguments rates <- cd_member_data(cache, "calculate_reporting_rate", args = list(admin_level = "adminlevel_1")) head(rates)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # a precomputed result cd_member_data(cache, "reporting_rate_national") # a method, with its arguments rates <- cd_member_data(cache, "calculate_reporting_rate", args = list(admin_level = "adminlevel_1")) head(rates)
Lists the constants the package's methodology uses (cutoffs, thresholds, default rates and targets) with the values the code runs with, so the documentation can be generated from them.
cd_methodology_defaults(group = c("all", "rmncah", "vaccine"))cd_methodology_defaults(group = c("all", "rmncah", "vaccine"))
group |
Which entries to return: |
A tibble with one row per constant and the columns:
id: a stable snake_case identifier.
step: one of "data_quality", "adjustment", "denominators",
"coverage", "subnational", "mortality".
group: "both", "rmncah" or "vaccine".
value: a list column; each element is a number, a string or a vector.
unit: for example "%", "x MAD", "ratio", "proportion", or "".
label: a short English label.
note: one English sentence on how the app uses it.
source: the file of the package (within R/) that uses it.
cd_methodology_defaults() cd_methodology_defaults("vaccine")cd_methodology_defaults() cd_methodology_defaults("vaccine")
ggplot2::theme_minimal() with a choice of grid lines, for the apps' light charts (cd2030.pooled's charts, the
subnational coverage dot plot and heat map).
cd_minimal_theme( base_size = 11, grid = c("all", "major", "x", "y", "none"), grid_colour = NULL )cd_minimal_theme( base_size = 11, grid = c("all", "major", "x", "y", "none"), grid_colour = NULL )
base_size |
The base font size, in points. The default is the size the charts of the apps are written in
(see |
grid |
Which grid lines to keep: |
grid_colour |
The colour of the lines |
A ggplot2 theme.
library(ggplot2) ggplot(mtcars, aes(mpg, factor(cyl))) + geom_point() + cd_minimal_theme(grid = "x")library(ggplot2) ggplot(mtcars, aes(mpg, factor(cyl))) + geom_point() + cd_minimal_theme(grid = "x")
Filters a named list or vector, such as a chart's legend labels or category labels, down to the entries named after a denominator the app offers. Labels are usually written for every denominator, and one the app does not offer must not appear in a chart.
cd_only_denominators(x)cd_only_denominators(x)
x |
A list or vector named by denominator id. |
x without the entries whose name is neither "un" (the UN projection, always kept) nor
one of the ids in cd_denominator_options(). The order and the type of x are kept.
labels <- c(un = "UN projection", dhis2 = "DHIS2 projection", other = "Not a denominator") cd_only_denominators(labels)labels <- c(un = "UN projection", dhis2 = "DHIS2 projection", other = "Not a denominator") cd_only_denominators(labels)
A filter chip that chooses the colour palette of the maps on a page. It belongs in the bar of map
options above the maps (cd_map_options()). The page reads the choice as input$<inputId> and
passes it to the map plots, which accept these palette names.
cd_palette_chip(inputId, i18n, first = "Greens")cd_palette_chip(inputId, i18n, first = "Greens")
inputId |
The input's id. Inside a module, pass it through the module's |
i18n |
The app's translator (a |
first |
The palette listed first, and so the one the page opens with: |
The choices are four sequential RColorBrewer palettes: "Greens", "Blues", "Reds"
and "Purples". The chip starts on its first choice, so first decides which palette a page
opens with. This is a plain input, not a module, so there is no server function to call.
The UI as Shiny tags (the chip). Its value, input$<inputId>, is the chosen palette's
name.
## Not run: cd_map_options(cd_palette_chip(ns("palette"), i18n, first = "Blues")) ## End(Not run)## Not run: cd_map_options(cd_palette_chip(ns("palette"), i18n, first = "Blues")) ## End(Not run)
Every chart in the package (each plot() method, the equiplots and plot_comparison()) changes its text and its
look in the same way, with the arguments below. They come after the arguments that say what to draw, and they
have the same names as the chart options (cd_chart_options()), so what is given for one chart can be given for
any other.
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
title, subtitle, caption, x_title, y_title and legend_title replace a chart's own text. NULL, the
default, keeps the text the chart writes itself. To remove a text, hide it: show_title = FALSE,
show_x_title = FALSE, show_legend_title = FALSE.
Everything else is a chart option, given by name in ...: the background (background_color, panel_color),
fonts and sizes (font_family, text_scale, title_size, axis_text_size), the axes (x_limits, y_limits,
x_text_angle, flip), the grid (grid, grid_color), the legend (legend_position, legend_labels,
show_legend) and the colours (colors). cd_chart_options() lists them all.
Make the options once and give them to each chart as options. A chart option named in the call wins over
options.
The six text arguments say what the chart should read; options holds what someone changed afterwards (in the
apps, with the chart's customize panel), so a text in options wins over the text argument. From least to most:
the chart's own text, the text arguments, options, and a chart option named in ....
x_axis and x_label were other names for x_title, y_axis and y_label for y_title, and legend and
fill_label for legend_title. They are no longer accepted: a chart given one stops and names the argument to
use.
## Not run: rates <- calculate_average_reporting_rate(data, admin_level = "adminlevel_1") # the same arguments on any chart plot(rates, title = "Reporting by region", y_title = "Region", legend_title = "Rate") plot(calculate_district_reporting_rate(data, 90), title = "Districts reporting", y_title = "Percent") # background and fonts plot(rates, background_color = "grey95", font_family = "serif", text_scale = 1.2) # one look for several charts look <- cd_chart_options(font_family = "serif", background_color = "grey95", legend_position = "right") plot(rates, options = look) plot(calculate_district_reporting_rate(data, 90), options = look) ## End(Not run)## Not run: rates <- calculate_average_reporting_rate(data, admin_level = "adminlevel_1") # the same arguments on any chart plot(rates, title = "Reporting by region", y_title = "Region", legend_title = "Rate") plot(calculate_district_reporting_rate(data, 90), title = "Districts reporting", y_title = "Percent") # background and fonts plot(rates, background_color = "grey95", font_family = "serif", text_scale = 1.2) # one look for several charts look <- cd_chart_options(font_family = "serif", background_color = "grey95", legend_position = "right") plot(rates, options = look) plot(calculate_district_reporting_rate(data, 90), options = look) ## End(Not run)
A filter chip that chooses the DHIS2 population the growth-projected denominators (ANC1 and Penta1 population growth) are built from. The choice is kept in the dataset.
cd_population_ui(id) cd_population_server(id, cache)cd_population_ui(id) cd_population_server(id, cache)
id |
The module's id. |
cache |
A reactive that returns the dataset, a CacheConnection. |
The choices are "totlivebirths_dhis2" (live births), "totbirths_dhis2" (total births),
"totpop_dhis2" (total population) and "totunder1_dhis2" (population under one year).
Once the chip is on the page, the server sets it to the dataset's value,
cache()$derivation_population, when there is one, and does so again whenever cache() changes.
Each choice the chip reports is saved with the dataset's set_derivation_population().
The ui takes no translator: its labels are translated with the translator the app registered with
cd_use_i18n().
cd_population_ui() returns the UI as Shiny tags (the chip).
cd_population_server() returns a reactive holding the chosen population's id as a string
(NULL until the chip has reported a value).
## Not run: # in a page's ui cd_population_ui(ns("population")) # in the page's server population <- cd_population_server("population", cache) ## End(Not run)## Not run: # in a page's ui cd_population_ui(ns("population")) # in the page's server population <- cd_population_server("population", cache) ## End(Not run)
Draws one cell of a table of rates, such as reporting rates: a small coloured shape that says how
good the rate is, followed by the rate rounded to a whole number. The shape differs with the
status as well as the colour, so the status never depends on colour alone. Use it as the cell
of a reactable::colDef(), for example in the columns of cd_table_server().
cd_rate_status_cell(value)cd_rate_status_cell(value)
value |
The rate, a single number on a scale of 0 to 100. |
The status has fixed limits: a red triangle below 70, an amber diamond from 70 to below 90, and a green circle from 90.
The cell as a Shiny tag (a span holding the shape and the number), or "" when value
is NULL or NA.
cd_rate_status_cell(64.2) cd_rate_status_cell(95) cd_rate_status_cell(NA) # as the cell of a table column reactable::colDef(cell = cd_rate_status_cell)cd_rate_status_cell(64.2) cd_rate_status_cell(95) cd_rate_status_cell(NA) # as the cell of a table column reactable::colDef(cell = cd_rate_status_cell)
What the report builder (datasuite.ui) needs from a Countdown dataset: its charts and tables drawn in the report's
look, the pictures and templates kept in it, its saved chart options, its fields (country, coverage values), years,
regions and flag. Every report function accepts the dataset itself too (datasuite.ui::as_report_context()).
cd_report_context(cache)cd_report_context(cache)
cache |
A report context (datasuite.ui::report_context()).
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) context <- cd_report_context(cache) context$years() context$fields(NULL, "en")$countrypath <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) context <- cd_report_context(cache) context$years() context$fields(NULL, "en")$country
Inside DataSuite (an app it started), asks it to install them: it shows the progress in its status bar and then
offers to restart the app. Outside DataSuite it does nothing; install them with cd_bayes_install_command().
cd_request_bayes_packages(packages = cd_bayes_packages_missing())cd_request_bayes_packages(packages = cd_bayes_packages_missing())
packages |
The packages to install, by default the missing ones. |
TRUE when DataSuite was asked, invisibly.
## Not run: # in an app DataSuite started, before the model is first used if (length(cd_bayes_packages_missing()) > 0) { cd_request_bayes_packages() } # one package only cd_request_bayes_packages("bayescoveragedeploy") ## End(Not run)## Not run: # in an app DataSuite started, before the model is first used if (length(cd_bayes_packages_missing()) > 0) { cd_request_bayes_packages() } # one package only cd_request_bayes_packages("bayescoveragedeploy") ## End(Not run)
Builds the name of the .rds file a finished dataset is saved to: <stem>_<group>.rds, for
example Benin_rmncah.rds or Benin_vaccine.rds. One source file can be loaded by more than
one app, and the group in the name keeps each app's finished copy apart.
cd_saved_copy_name(stem)cd_saved_copy_name(stem)
stem |
The name of the source file without its extension, a string. |
The file name (not a full path), a string. The group is the one
cd_wizard_indicator_group() returns.
old <- options(cd2030.app_group = "rmncah") cd_saved_copy_name("Kenya") cd_saved_copy_name(tools::file_path_sans_ext(basename("C:/data/Kenya_2024.xlsx"))) options(old)old <- options(cd2030.app_group = "rmncah") cd_saved_copy_name("Kenya") cd_saved_copy_name(tools::file_path_sans_ext(basename("C:/data/Kenya_2024.xlsx"))) options(old)
A scope says at which geography a page runs its analysis: which admin level and region filters
the page shows, and what admin level and region it hands to the analysis. Pages that run the same
analysis at a different geography (national coverage and sub-national coverage, for example)
differ only in their scope. Pass the result to cd_scoped_page_ui() and
cd_scoped_page_server(), or to cd_scope_filters() and cd_scope_server().
cd_scope( kind = c("national", "level", "region", "level_region"), fixed_level = NULL, show_district = FALSE )cd_scope( kind = c("national", "level", "region", "level_region"), fixed_level = NULL, show_district = FALSE )
kind |
The kind of scope: |
fixed_level |
An admin level (for example |
show_district |
Logical. For |
The kinds of scope:
"national": no filters. The analysis gets the admin level "national" and no region.
"level": an admin level chip only (admin level 1 or district). The analysis gets the chosen
level and no region.
"region": a region chip only, listing the admin level 1 areas. The analysis gets the chosen
area and the admin level "adminlevel_1", or fixed_level when it is given.
"level_region": an admin level chip and a region chip. The region chip is shown at admin
level 1, and also at the district level when show_district is TRUE.
A list with the elements kind, fixed_level and show_district, as given.
cd_scope() cd_scope("region", fixed_level = "district") cd_scope("level_region", show_district = TRUE)cd_scope() cd_scope("region", fixed_level = "district") cd_scope("level_region", show_district = TRUE)
The filter bar holding the admin level and region chips a scope asks for. cd_scoped_page_ui()
uses it. Call it yourself in a page that lays out its own body but still takes its geography from
a scope, and pair it with cd_scope_server().
cd_scope_filters(ns, i18n, scope)cd_scope_filters(ns, i18n, scope)
ns |
The page's namespace function, |
i18n |
The app's translator (a |
scope |
The page's scope, from |
The chips are an admin level filter (cd_admin_level_ui()) with the id ns("scope").
So in the page's module server, call cd_scope_server("scope", ...) with the same scope.
The UI as Shiny tags (a filter bar), or NULL for a "national" scope, which has no
filters.
## Not run: scope <- cd_scope("level_region") my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_scope_filters(ns, i18n, scope), my_cards(ns)) } ## End(Not run)## Not run: scope <- cd_scope("level_region") my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_scope_filters(ns, i18n, scope), my_cards(ns)) } ## End(Not run)
The server half of cd_scope_filters(): it gives the admin level and the region a scope resolves
to, as two reactives ready to hand to an analysis. Call it inside the page's module server.
cd_scoped_page_server() does this for a whole scoped page.
cd_scope_server(id, cache, i18n, scope)cd_scope_server(id, cache, i18n, scope)
id |
The id of the scope's filter within the page's module. Use |
cache |
A reactive that returns the dataset, a CacheConnection. |
i18n |
The app's translator (a |
scope |
The page's scope, from |
For a "national" scope nothing is read from the page. For the other kinds it runs the
admin level filter (cd_admin_level_server()) with the settings the scope asks for, so the two
reactives wait until that filter has a value.
A list of two reactives:
admin_level: "national" for a national scope. Otherwise the scope's fixed_level when it
has one, else the level of the filter ("adminlevel_1" or "district").
region: the name of the chosen area, or NULL when the scope has no region chip.
## Not run: my_page_server <- function(id, cache, i18n) { moduleServer(id, function(input, output, session) { geo <- cd_scope_server("scope", cache, i18n, cd_scope("level_region")) observe(print(list(geo$admin_level(), geo$region()))) }) } ## End(Not run)## Not run: my_page_server <- function(id, cache, i18n) { moduleServer(id, function(input, output, session) { geo <- cd_scope_server("scope", cache, i18n, cd_scope("level_region")) observe(print(list(geo$admin_level(), geo$region()))) }) } ## End(Not run)
Builds a page from an analysis module and a scope: the page's header and body, the scope's filter
bar, and the analysis module inside. Pages that run the same analysis at a different geography
then differ only in the scope they pass (see cd_scope()), and the filter bar and its wiring are
written once.
cd_scoped_page_ui(id, i18n, scope, inner_ui, ...) cd_scoped_page_server( id, cache, i18n, scope, inner_server, active = reactive(TRUE) )cd_scoped_page_ui(id, i18n, scope, inner_ui, ...) cd_scoped_page_server( id, cache, i18n, scope, inner_server, active = reactive(TRUE) )
id |
The module's id, which is also the page's id in the app's page registry. |
i18n |
The app's translator (a |
scope |
The page's scope, from |
inner_ui |
The analysis module's ui function, called as |
... |
More arguments for |
cache |
A reactive that returns the dataset, a CacheConnection. |
inner_server |
The analysis module's server function, called as
|
active |
A reactive that is |
The analysis module is the app's own pair of functions:
inner_ui(id, i18n, ...) returns the page's cards.
inner_server(id, cache, i18n, admin_level, region, active = ) takes the admin level and the
region as two reactives (see cd_scope_server() for what they hold).
Both are called with the id "body" inside the page's namespace. The page's title, section and
subtitle come from the app's page registry, so id must be the id of a registered page.
cd_scoped_page_ui() returns the page's UI as Shiny tags.
cd_scoped_page_server() returns what inner_server returns.
## Not run: scope <- cd_scope("region", fixed_level = "district") subnational_target_ui <- function(id, i18n) { cd_scoped_page_ui(id, i18n, scope, target_ui) } subnational_target_server <- function(id, cache, i18n, active = reactive(TRUE)) { cd_scoped_page_server(id, cache, i18n, scope, target_server, active) } ## End(Not run)## Not run: scope <- cd_scope("region", fixed_level = "district") subnational_target_ui <- function(id, i18n) { cd_scoped_page_ui(id, i18n, scope, target_ui) } subnational_target_server <- function(id, cache, i18n, active = reactive(TRUE)) { cd_scoped_page_server(id, cache, i18n, scope, target_server, active) } ## End(Not run)
Sets the R session's future plan to multisession, so that the Bayesian page fits its models
in other R processes and the app stays usable meanwhile. It changes the plan only while the plan
is the default (sequential): a session that already has a plan of its own keeps it, and a
second call does nothing. There is one worker by default, so a fit asked for while another runs
waits its turn. options(cd2030.bayes_workers = ) sets another number (at least one is always
used).
cd_start_bayes_workers()cd_start_bayes_workers()
The session's future plan, invisibly.
## Not run: cd_start_bayes_workers() future::nbrOfWorkers() # two fits at a time: set the option before the first call options(cd2030.bayes_workers = 2) cd_start_bayes_workers() ## End(Not run)## Not run: cd_start_bayes_workers() future::nbrOfWorkers() # two fits at a time: set the option before the first call options(cd2030.bayes_workers = 2) cd_start_bayes_workers() ## End(Not run)
The serverInput function given to cd_tabbed_charts_server() receives the indicator of its tab
as a string, and for the Custom tab as a reactive that returns the indicator the reader chose.
cd_tab_indicator() gives one way to read both.
cd_tab_indicator(indicator)cd_tab_indicator(indicator)
indicator |
What |
A function with no arguments that returns the indicator's code. For the Custom tab it
must be called where a reactive can be read (in a reactive(), a render function or a
plot_fun).
ind <- cd_tab_indicator("penta3") ind() ## Not run: # in a page's server: one serverInput for the indicators' tabs and the Custom tab cd_tabbed_charts_server("panel", serverInput = function(id, current_indicator) { ind <- cd_tab_indicator(current_indicator) cd_coverage_plot_server( id = id, filename = reactive(paste0(ind(), "_coverage")), data_fn = reactive(cache()$get_filtered_coverage(ind(), "national")), sheet_name = reactive(i18n$t(paste0("opt_", ind()))), i18n = i18n ) } ) ## End(Not run)ind <- cd_tab_indicator("penta3") ind() ## Not run: # in a page's server: one serverInput for the indicators' tabs and the Custom tab cd_tabbed_charts_server("panel", serverInput = function(id, current_indicator) { ind <- cd_tab_indicator(current_indicator) cd_coverage_plot_server( id = id, filename = reactive(paste0(ind(), "_coverage")), data_fn = reactive(cache()$get_filtered_coverage(ind(), "national")), sheet_name = reactive(i18n$t(paste0("opt_", ind()))), i18n = i18n ) } ) ## End(Not run)
A card that shows the same chart for several indicators, one tab each, with a "Custom" tab where
the reader chooses any other indicator. The page says how one chart is drawn (uiInput and
serverInput), and this module makes the tabs, switches between them and puts the chart tools of
the tab on show in the card's header. Many analysis pages are built from it.
cd_tabbed_charts_ui( id, i18n, title_key, uiInput, indicators = NULL, customIndicators = get_analysis_indicators(), showCustom = TRUE, width = 12 ) cd_tabbed_charts_server( id, serverInput, indicators = NULL, customIndicators = get_analysis_indicators(), showCustom = TRUE, selected_tab = reactive(NULL), i18n = cd_i18n() )cd_tabbed_charts_ui( id, i18n, title_key, uiInput, indicators = NULL, customIndicators = get_analysis_indicators(), showCustom = TRUE, width = 12 ) cd_tabbed_charts_server( id, serverInput, indicators = NULL, customIndicators = get_analysis_indicators(), showCustom = TRUE, selected_tab = reactive(NULL), i18n = cd_i18n() )
id |
The module's id. |
i18n |
The app's translator (a |
title_key |
The translation key of the card's title. |
uiInput |
A function |
indicators |
A character vector of indicator codes, one tab each, in this order. |
customIndicators |
The indicators the Custom tab's chip offers, as |
showCustom |
Logical. |
width |
The card's width, passed to the kit's |
serverInput |
A function |
selected_tab |
A reactive that returns the key of a tab to show (an indicator's code or
|
uiInput and serverInput are the two halves of one chart, usually
cd_coverage_plot_ui() and a function that calls cd_coverage_plot_server():
uiInput(id, toolbar_inline = TRUE) is called once for each tab and returns that tab's chart.
It must leave the chart's tools out when toolbar_inline is TRUE, because the card's header
shows them. The header draws the tools with cd_coverage_plot_toolbar_ui(), so the chart must
be a cd_coverage_plot_ui() or use the same ids.
serverInput(id, indicator) starts the chart of one tab. It is called once for each indicator,
with the indicator's code as both arguments. For the Custom tab it is called once, with the
id "custom" and a reactive that returns the indicator the reader chose; read either with
cd_tab_indicator(). It runs inside this module, so id is used as it is, without ns().
A tab's label is the translation of opt_ followed by the indicator's code. The tabs that are
not on show are hidden, and Shiny does not draw a hidden chart.
Give indicators and showCustom the same values in the ui and the server call.
cd_tabbed_charts_ui() returns the UI as Shiny tags (the card).
cd_tabbed_charts_server() returns a reactive holding the key of the tab on show: an
indicator's code, or "custom".
## Not run: # in a page's ui cd_tabbed_charts_ui(ns("panel"), i18n, "title_coverage_national", cd_coverage_plot_ui, indicators = c("penta3", "measles1") ) # in the page's server cd_tabbed_charts_server("panel", serverInput = function(id, indicator) { cd_coverage_plot_server( id = id, filename = reactive(paste0(indicator, "_coverage")), data_fn = reactive(my_coverage_data(cache(), indicator)), sheet_name = reactive(i18n$t(paste0("opt_", indicator))), i18n = i18n ) }, indicators = c("penta3", "measles1") ) ## End(Not run)## Not run: # in a page's ui cd_tabbed_charts_ui(ns("panel"), i18n, "title_coverage_national", cd_coverage_plot_ui, indicators = c("penta3", "measles1") ) # in the page's server cd_tabbed_charts_server("panel", serverInput = function(id, indicator) { cd_coverage_plot_server( id = id, filename = reactive(paste0(indicator, "_coverage")), data_fn = reactive(my_coverage_data(cache(), indicator)), sheet_name = reactive(i18n$t(paste0("opt_", indicator))), i18n = i18n ) }, indicators = c("penta3", "measles1") ) ## End(Not run)
A card that shows a formatted table (a flextable) on screen, with two downloads in the card's
header: the table as a picture and its data as an Excel workbook. Use it for a table whose layout
matters, such as a scorecard. The Overall Score page uses it. For a plain table of data, use
cd_table_ui().
cd_table_card_ui(id, i18n, title, ..., width = 12) cd_table_card_server( id, i18n, data, table_fun, filename, sheet = "lbl_score_metric_header", about = NULL )cd_table_card_ui(id, i18n, title, ..., width = 12) cd_table_card_server( id, i18n, data, table_fun, filename, sheet = "lbl_score_metric_header", about = NULL )
id |
The module's id. |
i18n |
The app's translator (a |
title |
The card's title: text that is already translated ( |
... |
More arguments for the kit's |
width |
The card's width, passed to the kit's |
data |
A reactive that returns what the table shows. It is given to |
table_fun |
A function |
filename |
A reactive that returns the first part of the downloaded files' name. The date and time and the extension are added to it. |
sheet |
The translation key of the workbook's sheet name. Default
|
about |
What the table is, for the app's AI: |
The page gives the data and one function that turns it into a flextable. The table on
screen and the picture are drawn with the same function, so they always match. The picture is a
PNG file. The workbook holds data() on one sheet. Both files are named filename() followed by
the date and time.
The table is drawn once data() has a value. It is also registered with the app's AI bridge,
which can then list it and read its data.
cd_table_card_ui() returns the UI as Shiny tags (the card).
cd_table_card_server() returns nothing useful. It is called for what it does.
## Not run: # in a page's ui cd_table_card_ui(ns("score"), i18n, i18n$t("title_score_main"), status = "success") # in the page's server cd_table_card_server("score", i18n, data = reactive(my_scores(cache())), table_fun = function(d) flextable::flextable(d), filename = reactive("overall_score") ) ## End(Not run)## Not run: # in a page's ui cd_table_card_ui(ns("score"), i18n, i18n$t("title_score_main"), status = "success") # in the page's server cd_table_card_server("score", i18n, data = reactive(my_scores(cache())), table_fun = function(d) flextable::flextable(d), filename = reactive("overall_score") ) ## End(Not run)
A card that shows a data frame as a table, with a control above it (a year chip or an indicator
chip) and a download of the data as an Excel workbook in the card's header. The module translates
the column headings it knows, rounds the numbers and aligns them. Use it for the table that goes
with a page's charts. For a formatted table (a flextable), use cd_table_card_ui().
cd_table_ui( id, i18n, title_key, control_type = c("year", "indicator"), width = 6 ) cd_table_server( id, cache, i18n, data, columns = NULL, control_type = c("year", "indicator"), filename = reactive("download"), label_key = "btn_global_download_data", extension = reactive("xlsx"), data_transform = NULL, excel_write_fun = NULL, excel_sheet = NULL, excel_title = NULL, about = NULL )cd_table_ui( id, i18n, title_key, control_type = c("year", "indicator"), width = 6 ) cd_table_server( id, cache, i18n, data, columns = NULL, control_type = c("year", "indicator"), filename = reactive("download"), label_key = "btn_global_download_data", extension = reactive("xlsx"), data_transform = NULL, excel_write_fun = NULL, excel_sheet = NULL, excel_title = NULL, about = NULL )
id |
The module's id. |
i18n |
The app's translator (a |
title_key |
The translation key of the card's title. |
control_type |
The control above the table: |
width |
The card's width, passed to the kit's |
cache |
A reactive that returns the dataset, a CacheConnection. |
data |
A reactive that returns the data frame the table shows. |
columns |
A named list of |
filename |
A reactive that returns the first part of the downloaded file's name. Default
|
label_key |
The translation key of the download button's label. Default
|
extension |
A reactive that returns the downloaded file's extension. Default
|
data_transform |
A function |
excel_write_fun |
A function |
excel_sheet |
The translation key of the sheet's name, for a download that holds |
excel_title |
The translation key of a title written above the data on that sheet. Used only
with |
about |
What the table is, for the app's AI: |
The control. Give control_type the same value in the ui and the server call.
"year": a chip listing the dataset's years (cache()$data_years), which starts on the first
of them. When the data has a year column, the table shows only the rows of the chosen year.
"indicator": an indicator chip (cd_indicator_ui()) offering every indicator. The module
does not filter by it. The page reads the chosen indicator from the reactive the server returns
and builds data from it.
The columns. These headings are translated without the page doing anything: year,
adminlevel_1, district and month; columns whose name starts with cov_ (coverage); columns
whose name ends with _med or _mad (median and MAD of an indicator) and the indicator's own
column beside them; and, with the indicator control, the column named after the chosen indicator.
Every other column keeps its name unless columns gives it a heading. Numbers are shown rounded
to whole numbers and aligned to the right, except year and month.
The download. The file is an Excel workbook named filename(), then the control's value,
then the date and time. What it holds depends on the arguments:
With excel_write_fun, that function writes the workbook from data().
Else with excel_sheet, data() is written on one sheet with that name, under excel_title
when it is given.
With neither, the data the table is drawn from (data() after data_transform) is written on
one sheet named "Data".
With a year control the download holds the year the control is on, as the table does and as the file's name says.
The table is also registered with the app's AI bridge, which can then list it and read its data.
cd_table_ui() returns the UI as Shiny tags (the card).
cd_table_server() returns a reactive holding the control's value: the chosen year as a
string, or the chosen indicator's code.
## Not run: # in a page's ui cd_table_ui(ns("rates"), i18n, "title_rr_main", control_type = "year") # in the page's server year <- cd_table_server("rates", cache, i18n, data = reactive(my_rates(cache())), columns = list(anc_rr = reactable::colDef(name = "ANC", cell = cd_rate_status_cell)), filename = reactive("reporting_rate"), excel_sheet = "title_rr_main" ) ## End(Not run)## Not run: # in a page's ui cd_table_ui(ns("rates"), i18n, "title_rr_main", control_type = "year") # in the page's server year <- cd_table_server("rates", cache, i18n, data = reactive(my_rates(cache())), columns = list(anc_rr = reactable::colDef(name = "ANC", cell = cd_rate_status_cell)), filename = reactive("reporting_rate"), excel_sheet = "title_rr_main" ) ## End(Not run)
The one scale the charts of the Countdown apps are written in, for a chart drawn outside the package that is to look like them.
cd_type_scale()cd_type_scale()
A named list: title, subtitle, axis_title, axis_text, legend, strip and caption in points
(for ggplot2::element_text()); label and label_small in millimetres (the size of
ggplot2::geom_text()).
cd_type_scale()$titlecd_type_scale()$title
The whole Load Data screen of a Countdown app: the page header, with its help button, and the
Load Data wizard with all seven steps. The server starts every step's server, builds the
steps' pages and hands them to wizard_steps_server(). The screen is the same for every app.
What differs between apps (the fields of the National Rates step and the reference-data
upload zones) comes from the app's options(cd2030.wizard = ...), which must be set before
the screen is used (see cd_wizard_config()). cd_app() uses this screen unless the app
passes its own upload_ui and upload_server.
cd_upload_data_ui(id, i18n, is_electron = FALSE) cd_upload_data_server(id, i18n, cdsuite_file, active)cd_upload_data_ui(id, i18n, is_electron = FALSE) cd_upload_data_server(id, i18n, cdsuite_file, active)
id |
The module's id. |
i18n |
The app's translator (a |
is_electron |
|
cdsuite_file |
The path of the file the app was started with, a string, or
|
active |
A reactive that returns |
The steps and their modules, in wizard order: Upload Data (upload_box_ui() and
reference_estimates_ui() in one card), Data Quality (data_quality_ui()), Survey Files
(survey_upload_ui()), National Rates (national_rates_ui()), Shapefile
(shapefile_step_ui()), Map Survey Files (map_survey_ui()) and Map Shapefile Names
(map_shapefile_ui()).
cd_upload_data_ui() returns the UI as Shiny tags: the page header and the wizard.
cd_upload_data_server() returns a list with two elements:
cache: a reactive value that holds the dataset, a CacheConnection, or NULL when
none is loaded;
requires_walkthrough: a reactive value that is TRUE when the wizard must be walked
through step by step, and FALSE when a saved dataset (.rds) was loaded.
## Not run: # the app describes its part of the wizard once, before the screen is used options(cd2030.app_group = "rmncah", cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) # in the app's ui cd_upload_data_ui("upload_data", i18n = i18n) # in the app's server: the dataset every page reads loaded <- cd_upload_data_server("upload_data", i18n, NA_character_, active = reactive(identical(input$tabs, "upload_data")) ) cache <- loaded$cache # cd_app() does both when it is given the pair cd_app(app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, upload_ui = cd_upload_data_ui, upload_server = cd_upload_data_server ) ## End(Not run)## Not run: # the app describes its part of the wizard once, before the screen is used options(cd2030.app_group = "rmncah", cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) # in the app's ui cd_upload_data_ui("upload_data", i18n = i18n) # in the app's server: the dataset every page reads loaded <- cd_upload_data_server("upload_data", i18n, NA_character_, active = reactive(identical(input$tabs, "upload_data")) ) cache <- loaded$cache # cd_app() does both when it is given the pair cd_app(app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, upload_ui = cd_upload_data_ui, upload_server = cd_upload_data_server ) ## End(Not run)
Sets the package's selected indicator group back to the app's group (with
set_selected_group()), then stops with an error when the dataset was built for a different
group. The group a dataset was built for is the indicator_group attribute of its
countdown_data. A dataset without that attribute, or a NULL dataset, passes.
cd_wizard_check_group(cache)cd_wizard_check_group(cache)
cache |
The dataset, a CacheConnection object (not a reactive), or |
TRUE, invisibly. The function stops with an error when the dataset was built for
another indicator group.
old <- options(cd2030.app_group = "rmncah") cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cd_wizard_check_group(cache) # no dataset passes too cd_wizard_check_group(NULL) options(old)old <- options(cd2030.app_group = "rmncah") cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cd_wizard_check_group(cache) # no dataset passes too cd_wizard_check_group(NULL) options(old)
Returns what an app has set for its own part of the Load Data wizard. The wizard is the same
for every indicator group except for two things, which an app describes once with
options(cd2030.wizard = list(...)) before the wizard is used: the fields of the National
Rates step and which reference-data upload zones the Upload Data step shows. The indicator
group is not part of this configuration (see cd_wizard_indicator_group()).
cd_wizard_config()cd_wizard_config()
An app sets the option like this:
options(cd2030.wizard = list(
national_rates_groups = list(cd_wizard_field_group(...), ...),
reference_uploads = c("un_estimates", "wuenic_estimates", "un_mortality_estimates")
))
national_rates_groups (required): the groups of fields of the National Rates step, in
display order. Each element is made with cd_wizard_field_group(), and each field in it
with cd_wizard_survey_field() (a survey coverage estimate, in percent) or
cd_wizard_rate_field() (a national rate, as a proportion). The wizard takes from these
the inputs it shows, what it saves to and reads back from the dataset, and which values
the step needs before it counts as complete: every field listed is required.
reference_uploads (optional): which reference-data zones the Upload Data step shows, any
of "un_estimates", "wuenic_estimates" and "un_mortality_estimates". The default is all
three.
The value of getOption("cd2030.wizard"), a list, with reference_uploads filled in
with its default when the app did not set it. The function stops with an error when the
option, or its national_rates_groups element, is not set.
old <- options(cd2030.wizard = list( national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ), reference_uploads = c("un_estimates", "wuenic_estimates") )) cfg <- cd_wizard_config() cfg$reference_uploads length(cfg$national_rates_groups[[1]]$fields) options(old)old <- options(cd2030.wizard = list( national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ), reference_uploads = c("un_estimates", "wuenic_estimates") )) cfg <- cd_wizard_config() cfg$reference_uploads length(cfg$national_rates_groups[[1]]$fields) options(old)
Puts fields under one heading for an app's wizard configuration. The National Rates step shows
each group as a titled block of number fields, in the order given (see cd_wizard_config()).
cd_wizard_field_group(title_key, subtitle_key, ...)cd_wizard_field_group(title_key, subtitle_key, ...)
title_key |
The translation key of the group's title, a string. |
subtitle_key |
The translation key of the group's subtitle, a string. |
... |
The fields of the group, in display order. Each argument is one field (from
|
A list with elements title_key, subtitle_key and fields (a flat list of the
fields).
group <- cd_wizard_field_group("title_upload_group_immunization", "sub_upload_group_immunization", cd_wizard_survey_field("penta3_prop", "penta3", "title_upload_penta3_survey"), cd_wizard_survey_field("measles1_prop", "measles1", "title_upload_measles1_survey") ) vapply(group$fields, function(f) f$key, character(1)) # a list of fields is added field by field group <- cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) length(group$fields)group <- cd_wizard_field_group("title_upload_group_immunization", "sub_upload_group_immunization", cd_wizard_survey_field("penta3_prop", "penta3", "title_upload_penta3_survey"), cd_wizard_survey_field("measles1_prop", "measles1", "title_upload_measles1_survey") ) vapply(group$fields, function(f) f$key, character(1)) # a list of fields is added field by field group <- cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) length(group$fields)
Returns the indicator group of the app, from options(cd2030.app_group = ...). When that
option is not set it falls back to getOption("cd2030.selected_group"). The wizard uses it
to build a dataset for the app's group and to name the dataset's saved copy.
cd_wizard_indicator_group()cd_wizard_indicator_group()
The indicator group, as the app set it (a string such as "rmncah" or "vaccine").
The function stops with an error when neither option is set.
old <- options(cd2030.app_group = "rmncah") cd_wizard_indicator_group() options(old)old <- options(cd2030.app_group = "rmncah") cd_wizard_indicator_group() options(old)
Returns the descriptions of the national rate fields that every app's National Rates step
has: pregnancy loss, twin rate, stillbirth rate, neonatal mortality rate and post-neonatal
mortality rate. Apps share this list so that their input ids, dataset keys and labels stay
the same. Pass it to cd_wizard_field_group().
cd_wizard_national_rate_fields()cd_wizard_national_rate_fields()
A list of five field descriptions, each made with cd_wizard_rate_field(), for the
national_estimates keys preg_loss, twin_rate, sbr, nmr and pnmr.
fields <- cd_wizard_national_rate_fields() vapply(fields, function(f) f$key, character(1)) vapply(fields, function(f) f$id, character(1))fields <- cd_wizard_national_rate_fields() vapply(fields, function(f) f$key, character(1)) vapply(fields, function(f) f$id, character(1))
Each function describes one number field for an app's wizard configuration (see
cd_wizard_config()). cd_wizard_survey_field() describes a survey coverage estimate, entered
in percent (0 to 100, in steps of 1) and saved in the dataset's survey_estimates.
cd_wizard_rate_field() describes a national rate, entered as a proportion (0 to 0.05, in
steps of 0.001) and saved in the dataset's national_estimates. Pass the results to
cd_wizard_field_group().
cd_wizard_survey_field(id, key, label_key) cd_wizard_rate_field(id, key, label_key)cd_wizard_survey_field(id, key, label_key) cd_wizard_rate_field(id, key, label_key)
id |
The input id of the field, a string. |
key |
The name of the value in the dataset, a string: an element of |
label_key |
The translation key of the field's label, a string. |
A list that describes the field, with elements kind ("survey" or "rate"), id,
key, label_key, min, max, step and hint (the translation key of the hint under
the field).
str(cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey")) str(cd_wizard_rate_field("stillbirth_rate", "sbr", "title_upload_stillbirth"))str(cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey")) str(cd_wizard_rate_field("stillbirth_rate", "sbr", "title_upload_stillbirth"))
Turns the value of a years chip (see cd_years_sync()) into the years to use. An empty chip
means "all years", and this returns every year for it, so the result can be saved in the dataset
and used to filter data as it is.
cd_years_input(value, all_years)cd_years_input(value, all_years)
value |
The chip's value ( |
all_years |
What "all years" is: the years in the dataset. |
An integer vector: the years in value, or all_years (as integers) when value holds
no year.
cd_years_input(c("2021", "2023"), all_years = 2019:2023) cd_years_input("", all_years = 2019:2023)cd_years_input(c("2021", "2023"), all_years = 2019:2023) cd_years_input("", all_years = 2019:2023)
The server half of a filter chip that chooses several years. The chip itself is a multi-choice
chip the page draws (cd_chip_multi()). This function gives the chip its options, the years in
the data, and sets it to the years already chosen in the dataset. Choosing nothing in the chip
means "all years".
cd_years_sync(input, session, id = "years", years, selected)cd_years_sync(input, session, id = "years", years, selected)
input |
The module's |
session |
The module's |
id |
The chip's input id within the module. Default |
years |
A reactive that returns the years the chip offers, the years in the data. |
selected |
A reactive that returns the years chosen in the dataset. An empty or all- |
Call it once inside a module server. It sends the options and the chosen years to the
chip once the chip is on the page, and again when years() or selected() changes. It does not
send the chip what the chip already holds.
It only goes from the dataset to the chip. The page saves the reader's choice itself, with its
own observeEvent(input$years, ...), where cd_years_input() turns the chip's value into the
years it means.
Nothing useful (the observer it creates). It is called for what it does.
## Not run: # in a page's ui cd_chip_multi(ns("years"), "title_global_select_years", i18n = i18n) # in the page's server cd_years_sync(input, session, "years", years = reactive(cache()$data_years), selected = reactive(cache()$mapping_years) ) observeEvent(input$years, { cache()$set_mapping_years(cd_years_input(input$years, cache()$data_years)) }) ## End(Not run)## Not run: # in a page's ui cd_chip_multi(ns("years"), "title_global_select_years", i18n = i18n) # in the page's server cd_years_sync(input, session, "years", years = reactive(cache()$data_years), selected = reactive(cache()$mapping_years) ) observeEvent(input$years, { cache()$set_mapping_years(cd_years_input(input$years, cache()$data_years)) }) ## End(Not run)
Checks that the Admin sheet has the country and first_admin_level columns. Run it on
the sheet before the sheets are merged, so that a missing column is reported by name.
check_admin_columns(admin_data)check_admin_columns(admin_data)
admin_data |
A data frame. The cleaned Admin sheet, before the sheets are merged (the
admin element of |
NULL if both columns are present. Otherwise a character vector of length one,
named "x", with a message that lists the missing columns.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_admin_columns(admin) # A sheet without its country column check_admin_columns(admin[setdiff(names(admin), "country")])path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_admin_columns(admin) # A sheet without its country column check_admin_columns(admin[setdiff(names(admin), "country")])
Checks that no district is listed in the Admin sheet under more than one admin level 1 unit.
This is the part of check_district_consistency() that can run before the sheets are merged.
check_admin_pairing_consistency(admin_data)check_admin_pairing_consistency(admin_data)
admin_data |
A data frame. The cleaned Admin sheet, before the sheets are merged, with
|
Admin level 1 names are compared without regard to case or extra spaces.
NULL if every district has one admin level 1 name, or if the sheet lacks either
column. Otherwise a character vector of length one, named "x", with a message that lists
the districts.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_admin_pairing_consistency(admin) # The first district listed a second time, under another region again <- admin[1, ] again$first_admin_level <- "Western" check_admin_pairing_consistency(rbind(admin, again))path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_admin_pairing_consistency(admin) # The first district listed a second time, under another region again <- admin[1, ] again$first_admin_level <- "Western" check_admin_pairing_consistency(rbind(admin, again))
Checks that the country named in the Admin sheet is one the package supports. Run it before
the sheets are merged to report an unrecognized country early. new_countdown() stops with
an error on the same problem.
check_country_recognized(parts, admin_sheet_name)check_country_recognized(parts, admin_sheet_name)
parts |
A named list of cleaned per-sheet tibbles ( |
admin_sheet_name |
A string. The name of the Admin sheet within |
The check applies only when the country column holds exactly one distinct value, ignoring
missing values. More than one value is reported by check_single_country(). The name is
recognized when it is close to a name in the package's list of countries.
NULL if the country is recognized, if the Admin sheet has no country column, or
if the column does not hold exactly one value. Otherwise a character vector of length one,
named "x", with a message that gives the unrecognized name.
check_required_columns_presheet()
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_country_recognized(sheets$parts, sheets$admin_sheet_name) # A country the package has no reference data for parts <- sheets$parts parts[[sheets$admin_sheet_name]]$country <- "Atlantis" check_country_recognized(parts, sheets$admin_sheet_name)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_country_recognized(sheets$parts, sheets$admin_sheet_name) # A country the package has no reference data for parts <- sheets$parts parts[[sheets$admin_sheet_name]]$country <- "Atlantis" check_country_recognized(parts, sheets$admin_sheet_name)
Checks two things in the merged data: that each district belongs to one admin level 1 unit, and that each district appears in every year of the data. A district that fails either test has usually been renamed or misspelled in part of the workbook.
check_district_consistency(.data)check_district_consistency(.data)
.data |
A data frame. The merged and standardized dataset, with |
Admin level 1 names are compared without regard to case or extra spaces, so "North East"
and "north east" count as the same unit. The years a district must appear in are all the
distinct years in .data.
NULL if no problem is found. Otherwise a character vector with one or two messages,
each named "x": one that lists the districts with more than one admin level 1 name, and
one that lists the districts missing from at least one year.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_district_consistency(data) # A district spelled differently in one year renamed <- data renamed$district[renamed$district == "Baringo" & renamed$year == 2023] <- "Baringo County" check_district_consistency(renamed)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_district_consistency(data) # A district spelled differently in one year renamed <- data renamed$district[renamed$district == "Baringo" & renamed$year == 2023] <- "Baringo County" check_district_consistency(renamed)
Compares the districts in the Admin sheet with the districts in all the other sheets, in both directions. Run it on the unmerged sheets: merging keeps only the districts of one sheet, so a district that is missing from that sheet would be dropped without notice.
check_district_cross_sheet(parts, admin_sheet_name)check_district_cross_sheet(parts, admin_sheet_name)
parts |
A named list of cleaned per-sheet tibbles ( |
admin_sheet_name |
A string. The name of the Admin sheet within |
NULL if the districts match, or if the Admin sheet has no district column.
Otherwise a character vector with one or two messages, each named "x": one that lists
the districts found in another sheet but not in the Admin sheet, each with the sheets it
was found in, and one that lists the Admin sheet districts found in no other sheet.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_district_cross_sheet(sheets$parts, sheets$admin_sheet_name) # A district renamed in the Admin sheet only parts <- sheets$parts parts[[sheets$admin_sheet_name]]$district[1] <- "Baringo County" check_district_cross_sheet(parts, sheets$admin_sheet_name)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_district_cross_sheet(sheets$parts, sheets$admin_sheet_name) # A district renamed in the Admin sheet only parts <- sheets$parts parts[[sheets$admin_sheet_name]]$district[1] <- "Baringo County" check_district_cross_sheet(parts, sheets$admin_sheet_name)
Checks that each district in the Population sheet has a row for every year the sheet
covers. This is the part of check_district_consistency() that can run before the sheets
are merged.
check_district_year_completeness(population_data)check_district_year_completeness(population_data)
population_data |
A data frame. The cleaned Population sheet, before the sheets are
merged, with |
NULL if every district appears in every year, or if the sheet lacks either column.
Otherwise a character vector of length one, named "x", with a message that lists the
districts missing from at least one year.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) population <- sheets$parts[[sheets$population_sheet_name]] check_district_year_completeness(population) # A district with no population row for one year gap <- population$district == "Baringo" & population$year == 2023 check_district_year_completeness(population[!gap, ])path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) population <- sheets$parts[[sheets$population_sheet_name]] check_district_year_completeness(population) # A district with no population row for one year gap <- population$district == "Baringo" & population$year == 2023 check_district_year_completeness(population[!gap, ])
Finds the indicators of the selected indicator group whose column is missing in every row of the dataset. An indicator with no data cannot be analysed.
check_indicator_emptiness(.data)check_indicator_emptiness(.data)
.data |
A data frame. The merged dataset, with one column per indicator. |
Only indicator columns that are present in .data are examined. An indicator whose column
is absent is not reported here.
A character vector of the names of the empty indicators. It has length zero if there are none.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_indicator_emptiness(data) # An indicator that was never reported data$penta3 <- NA_real_ check_indicator_emptiness(data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_indicator_emptiness(data) # An indicator that was never reported data$penta3 <- NA_real_ check_indicator_emptiness(data)
Runs check_indicator_emptiness() on the service sheets, stacked together, before the
sheets are merged. An indicator is flagged when it is missing in every row of every service
sheet.
check_indicator_emptiness_presheet(parts, service_sheet_names)check_indicator_emptiness_presheet(parts, service_sheet_names)
parts |
A named list of cleaned per-sheet tibbles ( |
service_sheet_names |
A character vector. The names of the service data sheets within
|
A character vector of the names of the empty indicators. It has length zero if there are none.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_indicator_emptiness_presheet(sheets$parts, sheets$service_sheet_names)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_indicator_emptiness_presheet(sheets$parts, sheets$service_sheet_names)
Finds the calendar months that the service sheets label with more than one text, for example
"January" in one sheet and "Janvier" in another. The data loads correctly either way,
because the month names are standardized. The result shows that the workbook mixes
languages or spellings, which is worth knowing about how it was put together.
check_month_language_consistency(parts, service_sheet_names)check_month_language_consistency(parts, service_sheet_names)
parts |
A named list of cleaned per-sheet tibbles ( |
service_sheet_names |
A character vector. The names of the service data sheets within
|
A tibble with one row per month that has more than one distinct original text, and
columns month (the standardized month name) and variants (the distinct original texts,
sorted and separated by commas). It has no rows if no month qualifies, or if the service
sheets lack a month or raw_month column.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_language_consistency(sheets$parts, sheets$service_sheet_names) # One service sheet that names January in French parts <- sheets$parts sheet <- sheets$service_sheet_names[2] parts[[sheet]]$raw_month[parts[[sheet]]$month == "January"] <- "Janvier" check_month_language_consistency(parts, sheets$service_sheet_names)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_language_consistency(sheets$parts, sheets$service_sheet_names) # One service sheet that names January in French parts <- sheets$parts sheet <- sheets$service_sheet_names[2] parts[[sheet]]$raw_month[parts[[sheet]]$month == "January"] <- "Janvier" check_month_language_consistency(parts, sheets$service_sheet_names)
Checks that each district has a row for every calendar month of every year it appears in. A missing month leaves a gap in the monthly series the analysis relies on.
check_month_presence(.data)check_month_presence(.data)
.data |
A data frame with |
NULL if no month is missing. Otherwise a character vector of length one, named
"x", with a message that lists the missing months as district year/month. The message
lists the first 10 and gives a count of the rest.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_month_presence(data) # One month of one district-year dropped gap <- data$district == "Baringo" & data$year == 2023 & data$month == "March" check_month_presence(data[!gap, ])path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_month_presence(data) # One month of one district-year dropped gap <- data$district == "Baringo" & data$year == 2023 & data$month == "March" check_month_presence(data[!gap, ])
Runs check_month_presence() on the service sheets, stacked together, before the sheets
are merged. A district-year passes when its 12 months are present across the service sheets
taken together.
check_month_presence_presheet(parts, service_sheet_names)check_month_presence_presheet(parts, service_sheet_names)
parts |
A named list of cleaned per-sheet tibbles ( |
service_sheet_names |
A character vector. The names of the service data sheets within
|
NULL if no month is missing. Otherwise a character vector of length one, named
"x", with a message that lists the missing months as district year/month. The message
lists the first 10 and gives a count of the rest.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_presence_presheet(sheets$parts, sheets$service_sheet_names) # March left out of every service sheet parts <- sheets$parts for (sheet in sheets$service_sheet_names) { parts[[sheet]] <- parts[[sheet]][parts[[sheet]]$month != "March", ] } check_month_presence_presheet(parts, sheets$service_sheet_names)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_presence_presheet(sheets$parts, sheets$service_sheet_names) # March left out of every service sheet parts <- sheets$parts for (sheet in sheets$service_sheet_names) { parts[[sheet]] <- parts[[sheet]][parts[[sheet]]$month != "March", ] } check_month_presence_presheet(parts, sheets$service_sheet_names)
Checks the merged data for rows whose month could not be read as a calendar month, for
example because of a typo or a month name in a language that is not supported. Such rows
have a missing month and would otherwise stay in the data unnoticed.
check_month_validity(.data)check_month_validity(.data)
.data |
A data frame. The merged and standardized dataset, with a |
A row is a problem when its month is NA. If .data has a raw_month column (the month
text as it was in the workbook), the message lists the distinct unrecognized values. If it
does not, as with a Stata master dataset, or if those values are all missing, the message
gives the number of affected rows instead.
NULL if every month is recognized, or if .data has no month column. Otherwise
a character vector of length one, named "x", with the message.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_month_validity(data) # Months that could not be read are missing after loading data$month[1:3] <- NA check_month_validity(data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_month_validity(data) # Months that could not be read are missing after loading data$month[1:3] <- NA check_month_validity(data)
Checks the service sheets, before they are merged, for rows whose month could not be read as a calendar month, for example because of a typo or a month name in a language that is not supported.
check_month_validity_presheet(parts, service_sheet_names)check_month_validity_presheet(parts, service_sheet_names)
parts |
A named list of cleaned per-sheet tibbles ( |
service_sheet_names |
A character vector. The names of the service data sheets within
|
A row is a problem when its month is NA. If the sheets have a raw_month column (the
month text as it was in the workbook, which load_excel_parts() keeps), the message lists
the distinct unrecognized values. If they do not, or if those values are all missing, the
message gives the number of affected rows instead.
NULL if every month is recognized, or if the service sheets have no month
column. Otherwise a character vector of length one, named "x", with the message.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_validity_presheet(sheets$parts, sheets$service_sheet_names) # A month the workbook misspells is read as missing parts <- sheets$parts sheet <- sheets$service_sheet_names[1] typo <- parts[[sheet]]$month == "March" parts[[sheet]]$raw_month[typo] <- "Mrch" parts[[sheet]]$month[typo] <- NA check_month_validity_presheet(parts, sheets$service_sheet_names)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_month_validity_presheet(sheets$parts, sheets$service_sheet_names) # A month the workbook misspells is read as missing parts <- sheets$parts sheet <- sheets$service_sheet_names[1] typo <- parts[[sheet]]$month == "March" parts[[sheet]]$raw_month[typo] <- "Mrch" parts[[sheet]]$month[typo] <- NA check_month_validity_presheet(parts, sheets$service_sheet_names)
Finds district-years where the monthly institutional live births (instlivebirths) equal the
annual population live births (live_births) in every month. Monthly counts normally vary,
so this pattern suggests that population figures were entered in a service data sheet.
check_population_service_collision(.data)check_population_service_collision(.data)
.data |
A data frame. The merged dataset, with |
Only months where both values are present are compared. A district-year is flagged when it has at least three such months and the two values are equal in all of them.
A tibble with columns district and year, one row per flagged district-year. It
has no rows if nothing is flagged or if .data lacks instlivebirths or live_births.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_population_service_collision(data) # Annual population births entered as the monthly service figure copied <- data$district == "Baringo" & data$year == 2023 data$instlivebirths[copied] <- data$live_births[copied] check_population_service_collision(data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) check_population_service_collision(data) # Annual population births entered as the monthly service figure copied <- data$district == "Baringo" & data$year == 2023 data$instlivebirths[copied] <- data$live_births[copied] check_population_service_collision(data)
Runs check_population_service_collision() on the unmerged sheets. It finds district-years
where the monthly institutional live births in the service sheets equal the annual live
births in the Population sheet in every month, which suggests that population figures were
entered in a service data sheet.
check_population_service_collision_presheet( parts, population_sheet_name, service_sheet_names )check_population_service_collision_presheet( parts, population_sheet_name, service_sheet_names )
parts |
A named list of cleaned per-sheet tibbles ( |
population_sheet_name |
A string. The name of the Population sheet within |
service_sheet_names |
A character vector. The names of the service data sheets within
|
The service sheets are stacked and the Population sheet's live_births is added to each
service row by district and year. Every service row is kept. A district-year is flagged
when it has at least three months with both values present and the two values are equal in
all of them.
A tibble with columns district and year, one row per flagged district-year. It
has no rows if nothing is flagged, if the Population sheet lacks district, year or
live_births, or if the service sheets lack instlivebirths.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_population_service_collision_presheet( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names ) # Baringo's 2023 population births entered in every month of the service sheet parts <- sheets$parts population <- parts[[sheets$population_sheet_name]] births <- population$live_births[population$district == "Baringo" & population$year == 2023] service <- parts[[sheets$service_sheet_names[1]]] service$instlivebirths[service$district == "Baringo" & service$year == 2023] <- births parts[[sheets$service_sheet_names[1]]] <- service check_population_service_collision_presheet( parts, sheets$population_sheet_name, sheets$service_sheet_names )path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_population_service_collision_presheet( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names ) # Baringo's 2023 population births entered in every month of the service sheet parts <- sheets$parts population <- parts[[sheets$population_sheet_name]] births <- population$live_births[population$district == "Baringo" & population$year == 2023] service <- parts[[sheets$service_sheet_names[1]]] service$instlivebirths[service$district == "Baringo" & service$year == 2023] <- births parts[[sheets$service_sheet_names[1]]] <- service check_population_service_collision_presheet( parts, sheets$population_sheet_name, sheets$service_sheet_names )
Compares, for each district-year, the estimated live births in the Population sheet with the institutional births reported in the service sheets. Not every birth happens in a facility, so an estimate that is lower than what facilities reported points to a problem in one of the two figures.
check_population_vs_births( parts, population_sheet_name, service_sheet_names, margin = 0.1 )check_population_vs_births( parts, population_sheet_name, service_sheet_names, margin = 0.1 )
parts |
A named list of cleaned per-sheet tibbles ( |
population_sheet_name |
A string. The name of the Population sheet within |
service_sheet_names |
A character vector. The names of the service data sheets within
|
margin |
A number between 0 and 1. The fraction by which the population figure may
fall short of the reported figure before it is flagged. Default is |
The reported figure is the sum over the months of a district-year of instlivebirths, or
of instdeliveries if the service sheets have no instlivebirths column. A district-year
is flagged when live_births is less than (1 - margin) times that sum. Only district-years
that have both figures are compared.
NULL if no district-year is flagged, if the Population sheet lacks district,
year or live_births, or if the service sheets have neither births column. Otherwise a
character vector of length one, named "x", with a message that lists the first 10 flagged
district-years and gives a count of the rest. Its "rows" attribute is a tibble of all the
flagged district-years, with columns district, year, live_births and
total_delivered (the reported sum).
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) found <- check_population_vs_births( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names ) found attr(found, "rows") # Flag any shortfall, however small check_population_vs_births( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names, margin = 0 )path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) found <- check_population_vs_births( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names ) found attr(found, "rows") # Flag any shortfall, however small check_population_vs_births( sheets$parts, sheets$population_sheet_name, sheets$service_sheet_names, margin = 0 )
Checks the unmerged sheets for every column the indicator group requires: the group's
indicators, a reporting rate for each of its categories, and the population columns. It
reports the same missing columns that new_countdown() stops on, before the sheets are merged.
check_required_columns_presheet(parts, group = get_selected_group())check_required_columns_presheet(parts, group = get_selected_group())
parts |
A named list of cleaned per-sheet tibbles ( |
group |
A string. The indicator group to check against. Default is the selected group. |
Only the column names are read. They are compared as they will be once the sheets are merged and standardized, so a column that standardization renames or computes is not reported as missing. The messages use the names the workbook uses.
NULL if no required column is missing, or if the sheets have no columns. Otherwise
a character vector with up to three messages, each named "x": one for the population
columns, one for the reporting rate columns and one for the indicator columns.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_required_columns_presheet(sheets$parts, group = "rmncah") # A Population sheet without its growth rate column parts <- sheets$parts parts[[sheets$population_sheet_name]]$pop_growth_rate <- NULL check_required_columns_presheet(parts, group = "rmncah")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) check_required_columns_presheet(sheets$parts, group = "rmncah") # A Population sheet without its growth rate column parts <- sheets$parts parts[[sheets$population_sheet_name]]$pop_growth_rate <- NULL check_required_columns_presheet(parts, group = "rmncah")
Finds the admin level 1 names in the dataset that have no close match among the regions of the shapefile. A dataset region without a shapefile match cannot be shown on a map.
check_shapefile_admin_names(shapefile, countdown_data, name_field = "NAME_1")check_shapefile_admin_names(shapefile, countdown_data, name_field = "NAME_1")
shapefile |
An |
countdown_data |
A data frame. The dataset, with an |
name_field |
A string. The column of |
Names are compared without regard to case or accents, using the Jaro-Winkler distance. A name is unmatched when its distance to the closest shapefile name is 0.25 or more. Shapefile regions that match no dataset name are not reported.
A tibble with one row per unmatched dataset name and columns name (the dataset
name), suggestion (the closest shapefile name) and distance (the distance between
them). It has no rows if every name matches, or if shapefile is NULL or has no
name_field column.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # The bundled shapefile has the counties, the dataset's regions are the former provinces check_shapefile_admin_names(cache$shapefile, cache$countdown_data) # With no shapefile there is nothing to compare check_shapefile_admin_names(NULL, cache$countdown_data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # The bundled shapefile has the counties, the dataset's regions are the former provinces check_shapefile_admin_names(cache$shapefile, cache$countdown_data) # With no shapefile there is nothing to compare check_shapefile_admin_names(NULL, cache$countdown_data)
Checks that the country column of the Admin sheet holds no more than one distinct value.
A dataset must belong to one country, so run this before the sheets are merged to get a
message that lists the values found.
check_single_country(admin_data)check_single_country(admin_data)
admin_data |
A data frame. The cleaned Admin sheet, with a |
Missing values are ignored. A sheet with no country value at all passes this check.
NULL if the sheet has at most one country value. Otherwise a character vector of
length one, named "x", with a message that lists the values.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_single_country(admin) # A row that belongs to another country admin$country[1] <- "Uganda" check_single_country(admin)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] check_single_country(admin) # A row that belongs to another country admin$country[1] <- "Uganda" check_single_country(admin)
Finds the admin level 1 names in the dataset that have no close match among the regions of the regional survey. A dataset region without a survey match cannot get a regional or equity estimate.
check_survey_admin_names(regional_survey, countdown_data)check_survey_admin_names(regional_survey, countdown_data)
regional_survey |
A data frame of regional survey data with an |
countdown_data |
A data frame. The dataset, with an |
Names are compared without regard to case or accents, using the Jaro-Winkler distance. A name is unmatched when its distance to the closest survey name is 0.25 or more. Survey regions that match no dataset name are not reported.
A tibble with one row per unmatched dataset name and columns name (the dataset
name), suggestion (the closest survey name) and distance (the distance between them).
It has no rows if every name matches, or if regional_survey is NULL or has no
adminlevel_1 column.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) data <- cache$countdown_data check_survey_admin_names(cache$regional_survey, data) # A region the survey calls something else data$adminlevel_1[data$adminlevel_1 == "Coast"] <- "Pwani" check_survey_admin_names(cache$regional_survey, data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) data <- cache$countdown_data check_survey_admin_names(cache$regional_survey, data) # A region the survey calls something else data$adminlevel_1[data$adminlevel_1 == "Coast"] <- "Pwani" check_survey_admin_names(cache$regional_survey, data)
clean_error_message processes and cleans error messages to remove unnecessary
details such as ANSI escape codes, CLI-specific bullets, stack traces, and
technical context. It ensures the input is a valid error object before processing
and returns a blank string ("") if the input is not an error.
clean_error_message(error_message)clean_error_message(error_message)
error_message |
The input to be processed. This should be an object of
class |
A cleaned, user-friendly error message as a string. Returns an empty string if the input is not an error object.
# Processing a Valid Error Message tryCatch( { stop("Something went wrong.") }, error = function(e) { cleaned <- clean_error_message(e) cleaned } ) # Handling Non-Error Input cleaned <- clean_error_message("This is not an error object") cleaned# Processing a Valid Error Message tryCatch( { stop("Something went wrong.") }, error = function(e) { cleaned <- clean_error_message(e) cleaned } ) # Handling Non-Error Input cleaned <- clean_error_message("This is not an error object") cleaned
compute_indicator_numerator aggregates the numerators for specified health
indicators across different administrative levels, such as national, and
and subnational The function groups data by year and the specified administrative
level and calculates the sum of the selected indicators.
compute_indicator_numerator( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL, show_district = TRUE )compute_indicator_numerator( .data, admin_level = c("national", "adminlevel_1", "district"), region = NULL, show_district = TRUE )
.data |
A tibble of class |
admin_level |
Character. Specifies the administrative level for aggregation.
Available options are: |
region |
Optional name of an |
show_district |
Logical. When |
A tibble containing yearly aggregated totals for each indicator at the specified administrative level.
## Not run: # Calculate national-level totals for health indicators national_totals <- compute_indicator_numerator(dhis2_data, admin_level = "national") # Calculate administrative-level 1 totals for health indicators region_totals <- compute_indicator_numerator(dhis2_data, admin_level = "adminlevel_1") # Calculate district-level totals for health indicators district_totals <- compute_indicator_numerator(dhis2_data, admin_level = "district") ## End(Not run)## Not run: # Calculate national-level totals for health indicators national_totals <- compute_indicator_numerator(dhis2_data, admin_level = "national") # Calculate administrative-level 1 totals for health indicators region_totals <- compute_indicator_numerator(dhis2_data, admin_level = "adminlevel_1") # Calculate district-level totals for health indicators district_totals <- compute_indicator_numerator(dhis2_data, admin_level = "district") ## End(Not run)
Calculates annualized service utilization statistics including outpatient (OPD), inpatient (IPD), case fatality rates, and under-5 service use, aggregated at national, admin level 1 or district level.
compute_service_utilization( .data, admin_level = c("national", "adminlevel_1", "district") )compute_service_utilization( .data, admin_level = c("national", "adminlevel_1", "district") )
.data |
A data frame containing service and population indicators. |
admin_level |
One of |
A cd_service_utilization object (tibble subclass) with summarized and derived indicators:
OPD/IPD totals and rates
Under-5 service utilization
Case fatality rates
Proportion of under-5 deaths
## Not run: compute_service_utilization(dat, admin_level = "national") ## End(Not run)## Not run: compute_service_utilization(dat, admin_level = "national") ## End(Not run)
Applies the step definitions to a dataset and returns, for each step, whether it is complete, locked, required and how it should show in the wizard's row of steps. The wizard's row of steps, its footer and the summary page all read this result.
compute_step_states( cd, current, requires_walkthrough = TRUE, step_defs = wizard_step_defs, acknowledged = character(0) )compute_step_states( cd, current, requires_walkthrough = TRUE, step_defs = wizard_step_defs, acknowledged = character(0) )
cd |
The dataset, a CacheConnection object (the value of |
current |
The key of the step the user is on, a string, or |
requires_walkthrough |
|
step_defs |
The steps, a list with the structure of wizard_step_defs, which is the
default. A step may also have a |
acknowledged |
The keys of the steps the user has moved on from with Continue or Skip, a character vector. |
On a walkthrough (requires_walkthrough = TRUE) a step is locked when the step before it is
not in acknowledged, or when any earlier required step is incomplete. Without a walkthrough
nothing is locked.
status is only for display. It is "locked" for a locked step, otherwise "current" for
the step named by current, otherwise "complete" when the step is complete, touched and in
acknowledged, and otherwise "available". To know whether a step's data is done, read
complete, not status: the current step never has the status "complete".
A list with one element per step, in the order of step_defs. Each element is a list
with:
key, title_key: copied from the step's definition.
status: "locked", "current", "complete" or "available" (see Details).
complete: TRUE when the step's complete_fn returns TRUE for cd.
touched: the result of the step's touched_fn, or the same as complete when the
step has none.
locked: TRUE when the user may not open the step yet.
relevant: the result of the step's relevant_fn, or TRUE when the step has none.
required: TRUE when the step must be complete before the user can go on.
old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # on a walkthrough, with the first two steps passed states <- compute_step_states(cache, current = "survey_files", acknowledged = c("upload", "quality") ) vapply(states, function(s) s$status, character(1)) # a finished dataset: nothing is locked states <- compute_step_states(cache, current = NULL, requires_walkthrough = FALSE) vapply(states, function(s) s$complete, logical(1)) options(old)old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # on a walkthrough, with the first two steps passed states <- compute_step_states(cache, current = "survey_files", acknowledged = c("upload", "quality") ) vapply(states, function(s) s$status, character(1)) # a finished dataset: nothing is locked states <- compute_step_states(cache, current = NULL, requires_walkthrough = FALSE) vapply(states, function(s) s$complete, logical(1)) options(old)
A card of charts that each compare two indicators, drawn by plot_comparison(). It has one tab
for each indicator pair the app sets (the consistency_pairs setting, see
consistency_pair_keys()), for example ANC1 against Penta1, and a Custom tab where the person
picks any two indicators to compare. It is the second card of the Internal consistency page
(internal_consistency_ui()). It reads countdown_data from the dataset.
consistency_check_ui(id, i18n) consistency_check_server(id, cache, i18n, active = reactive(TRUE))consistency_check_ui(id, i18n) consistency_check_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
consistency_check_ui() returns the card's UI as Shiny tags.
consistency_check_server() is called for its side effects.
## Not run: # the card in a page module, as the Internal consistency page uses it my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, consistency_check_ui(ns("consistency"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { consistency_check_server("consistency", cache, i18n, active = active) }) } ## End(Not run)## Not run: # the card in a page module, as the Internal consistency page uses it my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, consistency_check_ui(ns("consistency"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { consistency_check_server("consistency", cache, i18n, active = active) }) } ## End(Not run)
Gives the key of each indicator pair the Consistency checks card (consistency_check_ui())
compares. The pairs come from the app's consistency_pairs setting (see cd_cfg()). Without
that setting they are ANC1 with Penta1 and Penta1 with Penta3. The card has one tab per key,
followed by its "custom" tab, which is not in this list.
consistency_pair_keys()consistency_pair_keys()
A character vector with one key per pair, the two indicator codes joined by an
underscore ("anc1_penta1").
consistency_pair_keys() # the pairs an app sets old <- options(cd2030.config = list(consistency_pairs = list(c("anc1", "penta1"), c("opv1", "opv3")))) consistency_pair_keys() options(old)consistency_pair_keys() # the pairs an app sets old <- options(cd2030.config = list(consistency_pairs = list(c("anc1", "penta1"), c("opv1", "opv3")))) consistency_pair_keys() options(old)
Gives the label of one indicator pair's tab on the Consistency checks card
(consistency_check_ui()). The label is the pair's translation (the key opt_consist_<x>_<y>)
when the translator has one. Otherwise it is the two indicator codes in capitals joined by "and"
("ANC1 and PENTA1").
consistency_pair_label(i18n, pair)consistency_pair_label(i18n, pair)
i18n |
The app's translator (a |
pair |
A character vector of two indicator codes, the first for the x axis and the second
for the y axis ( |
The label: what i18n$t() gives for the pair's key when it is translated, otherwise a
character string.
## Not run: # i18n is the app's translator, as a page receives it consistency_pair_label(i18n, c("anc1", "penta1")) # the labels of every pair the app compares, named by tab key pairs <- cd_cfg("consistency_pairs", list(c("anc1", "penta1"), c("penta1", "penta3"))) labels <- vapply(pairs, function(pair) consistency_pair_label(i18n, pair), character(1)) setNames(labels, consistency_pair_keys()) ## End(Not run)## Not run: # i18n is the app's translator, as a page receives it consistency_pair_label(i18n, c("anc1", "penta1")) # the labels of every pair the app compares, named by tab key pairs <- cd_cfg("consistency_pairs", list(c("anc1", "penta1"), c("penta1", "penta3"))) labels <- vapply(pairs, function(pair) consistency_pair_label(i18n, pair), character(1)) setNames(labels, consistency_pair_keys()) ## End(Not run)
The Shiny pieces every Countdown app (cd2030.rmncah, cd2030.vaxx, and apps on a custom indicator group) is built
from, on datasuite.ui's interface kit. This page is the guide to them: what there is and how the pieces fit. Each
function has its own help page, with its arguments and what it returns, next to its code: pages in
R/page-<page id>.R (a page's part in R/page-<page id>--<part>.R), the Load Data wizard in R/wizard-*.R,
filters in R/filter-*.R, layout in R/layout-*.R, chart and table cards in R/chart-*.R and the app itself in
R/app-*.R. The kit's own components are described in datasuite.ui's docs/COMPONENTS.md.
The app. cd_app(app_name, app_version, theme, nav_sections, registry, i18n, language, selected_file, upload_ui, upload_server) returns the Shiny app: datasuite.ui's app_frame() with the Introduction and Load Data
screens, the dataset header (with its denominator row, cd_denominator_header()) and the app's pages. An app's
run_app() sets its options, builds its translator, lists its pages and nav tree, and calls it – see
cd2030.rmncah::run_app() for a complete one. The standard sidebar sections are cd_nav_start(),
cd_nav_quality(), cd_nav_denominators(), cd_nav_national() and cd_nav_subnational().
Per-app settings. An app sets options(cd2030.config = list(...)) once; the pages read it with
cd_cfg(key, default). Keys: nat_cov_indicators, target_indicators, equity_indicators,
cov_trend_indicators, sub_derived_indicators, survey_comp_indicators, adjustment_indicators, k_factors,
reporting_rate_indicators, reporting_rate_facet_ncol, consistency_pairs, has_maternal (see
R/app-config.R). The indicator group is pinned with set_selected_group() and
options(cd2030.app_group = ...); the Introduction page's help comes from options(cd2030.help_dir = ...).
Pages. Each is a <stem>_ui(id, i18n) / <stem>_server(id, cache, i18n, ...) pair taking the dataset
(CacheConnection) as a reactive:
data quality: data_quality, reporting_rate, data_completeness, outlier_detection, consistency_check,
internal_consistency, overall_score, calculate_ratios;
adjustment: data_adjustment (the years and areas removed are its first section), adjustment_changes;
denominators: denominator_assessment, denominator_selection, subnational_denominator;
national and sub-national analysis: national_coverage, subnational_coverage, coverage, coverage_trends,
national_inequality, subnational_inequality, inequality, equity, national_target, subnational_target,
target, survey_comparison, subnational_mapping.
The Introduction page (introduction_ui(id, i18n), introduction_server(id, selected_language)) shows the app's
help in the chosen language; cd_app() adds it.
The Load Data wizard. cd_upload_data_ui() / cd_upload_data_server() are the Load Data screen (cd_app()'s
default): the page header and the wizard, the same for every app, which describes its own part of it with
options(cd2030.wizard = list(national_rates_groups, reference_uploads)) (see R/wizard-config.R).
upload_box_*, wizard_steps_* and wizard_landing_* make the screen; its steps are
wizard_step_defs (upload, data quality, survey files, national rates, shapefile, survey and map mappings), each with
a step_*_complete() test, and compute_step_states() works out which are done, blocked or optional. The steps'
pages are national_rates_*, survey_upload_*, reference_estimates_*, shapefile_step_*, map_survey_* and
map_shapefile_*; cd_wizard_* build their fields.
Filters and building blocks. cd_admin_level_*, cd_indicator_*, cd_denominator_*, cd_population_*,
cd_years_input() / cd_years_sync(), the scoped page (cd_scope(), cd_scoped_page_*, cd_scope_filters()),
tabbed charts (cd_tabbed_charts_*), tables (cd_table_*), a flextable in a card with its picture and Excel
downloads (cd_table_card_*) and the coverage chart card (cd_coverage_plot_*).
cd_app() to build an app; reporting_rate_ui() for a page; cd_upload_data_ui() for the Load Data
wizard; cd_table_ui(), cd_scope() and cd_admin_level_ui() for building blocks.
## Not run: # an app's run_app(): its options, its translator, its pages and nav tree, then cd_app() options(cd2030.selected_group = "rmncah", cd2030.app_group = "rmncah") set_selected_group("rmncah") options(cd2030.config = list( reporting_rate_indicators = c("opt_anc" = "anc_rr", "opt_vacc" = "vacc_rr"), has_maternal = TRUE )) options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) i18n <- shiny.i18n::init_i18n(translation_json_path = cd_translations("translation.json")) i18n$set_translation_language("en") cd_use_i18n(i18n) pages <- list( cd_page_def( id = "reporting_rate", ui = reporting_rate_ui, server = reporting_rate_server, title = "title_rr_main", section = "lbl_nav_section_quality", subtitle = "sub_rr_main", help = c("apps/countdown/data-quality", "reporting-rate") ) ) cd_use_pages(pages) cd_app( app_name = "My Countdown app", app_version = "1.0.0", theme = "rmncah", nav_sections = list(cd_nav_start(), cd_nav_quality()), registry = pages, i18n = i18n, language = "en", selected_file = NA, upload_ui = cd_upload_data_ui, upload_server = cd_upload_data_server ) ## End(Not run)## Not run: # an app's run_app(): its options, its translator, its pages and nav tree, then cd_app() options(cd2030.selected_group = "rmncah", cd2030.app_group = "rmncah") set_selected_group("rmncah") options(cd2030.config = list( reporting_rate_indicators = c("opt_anc" = "anc_rr", "opt_vacc" = "vacc_rr"), has_maternal = TRUE )) options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) i18n <- shiny.i18n::init_i18n(translation_json_path = cd_translations("translation.json")) i18n$set_translation_language("en") cd_use_i18n(i18n) pages <- list( cd_page_def( id = "reporting_rate", ui = reporting_rate_ui, server = reporting_rate_server, title = "title_rr_main", section = "lbl_nav_section_quality", subtitle = "sub_rr_main", help = c("apps/countdown/data-quality", "reporting-rate") ) ) cd_use_pages(pages) cd_app( app_name = "My Countdown app", app_version = "1.0.0", theme = "rmncah", nav_sections = list(cd_nav_start(), cd_nav_quality()), registry = pages, i18n = i18n, language = "en", selected_file = NA, upload_ui = cd_upload_data_ui, upload_server = cd_upload_data_server ) ## End(Not run)
A card of the Denominator selection page (denominator_selection_ui()) with one tab per
indicator (the app's cov_trend_indicators setting). Each tab has a chart of the indicator's
coverage over the years, with one line per denominator the app offers, for the country or for
the chosen region. The card has no filters of its own: the page passes it the admin level and
the region. It calls the dataset's calculate_derived_coverage(), and draws nothing until the
dataset's check_inequality_params is TRUE.
coverage_trends_ui(id, i18n) coverage_trends_server( id, cache, admin_level, region, i18n, active = reactive(TRUE) )coverage_trends_ui(id, i18n) coverage_trends_server( id, cache, admin_level, region, i18n, active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A reactive that returns the admin level of the chart: |
region |
A reactive that returns the name of the chosen region, or |
active |
A reactive that is |
coverage_trends_ui() returns the card's UI as Shiny tags. coverage_trends_server()
is called for its side effects.
## Not run: # the card in a page that has an admin level filter, as the Denominator selection page does my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_filter_bar(cd_admin_level_ui(ns("admin_level"), i18n, include_national = TRUE)), coverage_trends_ui(ns("coverage"), i18n) ) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { admin <- cd_admin_parts(cd_admin_level_server("admin_level", cache, i18n)) coverage_trends_server("coverage", cache, admin$admin_level, admin$region, i18n, active = active) }) } ## End(Not run)## Not run: # the card in a page that has an admin level filter, as the Denominator selection page does my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_filter_bar(cd_admin_level_ui(ns("admin_level"), i18n, include_national = TRUE)), coverage_trends_ui(ns("coverage"), i18n) ) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { admin <- cd_admin_parts(cd_admin_level_server("admin_level", cache, i18n)) coverage_trends_server("coverage", cache, admin$admin_level, admin$region, i18n, active = active) }) } ## End(Not run)
The body of the national and sub-national coverage pages: one card of charts with a tab for each
indicator the app lists (cd_cfg("nat_cov_indicators")) and a Custom tab for any other analysis
indicator. A tab plots the indicator's coverage by year from the health facility data, with the
denominator selected for that indicator, beside the survey and WUENIC estimates. It reads the
dataset's get_filtered_coverage(), which takes the indicator's rows from calculate_coverage()
for the admin level and region. The tab "fpet", when an app lists it, shows the family planning
estimates instead (cache()$fpet_data, from 2010 onwards). The piece has no filters of its own:
the page gives it the admin level and region.
coverage_ui(id, i18n, key_label) coverage_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )coverage_ui(id, i18n, key_label) coverage_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
key_label |
The translation key of the card's title. |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A reactive that returns the level the coverage is worked out at: |
region |
A reactive that returns the name of the region (or district) to show, or |
active |
A reactive that is |
coverage_ui() returns the card's UI as Shiny tags. coverage_server() returns a
reactive that holds the key of the tab shown: an indicator's name, or "custom".
## Not run: # the charts in a page module, at national level my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, coverage_ui(ns("body"), i18n, "title_coverage_national")) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { coverage_server("body", cache, i18n, reactive("national"), active = active) }) } # for one region: the admin level and the region are reactives coverage_server("body", cache, i18n, reactive("adminlevel_1"), reactive("Nairobi"), active = active) ## End(Not run)## Not run: # the charts in a page module, at national level my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, coverage_ui(ns("body"), i18n, "title_coverage_national")) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { coverage_server("body", cache, i18n, reactive("national"), active = active) }) } # for one region: the admin level and the region are reactives coverage_server("body", cache, i18n, reactive("adminlevel_1"), reactive("Nairobi"), active = active) ## End(Not run)
Joins computed national mortality indicators with UN estimates, returns latest value per indicator.
create_mortality_ratios(.data, mortality_data)create_mortality_ratios(.data, mortality_data)
.data |
The main mortality dataset. |
mortality_data |
A |
A tibble of class cd_mortality_ratio with latest available values and UN means.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) mortality <- create_mortality_summary(cache$countdown_data) ratios <- create_mortality_ratios(mortality, cache$un_mortality_estimates) ratios # the institutional ratio against the UN estimate, by assumed completeness summarise_completeness_ratio(ratios, plot_type = "mmr")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) mortality <- create_mortality_summary(cache$countdown_data) ratios <- create_mortality_ratios(mortality, cache$un_mortality_estimates) ratios # the institutional ratio against the UN estimate, by assumed completeness summarise_completeness_ratio(ratios, plot_type = "mmr")
Combines national and admin level 1 summaries and formats as a custom class for plotting.
create_mortality_summary(.data)create_mortality_summary(.data)
.data |
An object of class |
A cd_mortality_summary tibble.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) mortality <- create_mortality_summary(data) mortality # the national rates mortality[mortality$adminlevel_1 == "National", c("year", "mmr_inst", "sbr_inst", "nn_inst")]path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) mortality <- create_mortality_summary(data) mortality # the national rates mortality[mortality$adminlevel_1 == "National", c("year", "mmr_inst", "sbr_inst", "nn_inst")]
The page where the person sets which data is kept for analysis and how it is corrected. Years can
be removed everywhere, and an area's data can be removed for some or every year. The corrections
are for completeness (by each indicator group's k factor), outliers and missing values, set for
everywhere or with a region's or district's own settings. The page is one editor
(datasuite.ui::cd_adjustment_editor()), which shows beside each setting what the check pages
found (adjustment_evidence()). Below it are a button that downloads the adjusted data as a
Stata file and a link to the Data adjustment changes page (adjustment_changes_ui()).
data_adjustment_ui(id, i18n) data_adjustment_server(id, cache, i18n, active = reactive(TRUE))data_adjustment_ui(id, i18n) data_adjustment_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
Not used. It is accepted so that the app's page registry can pass it as it does to every other page. |
The Adjust data button saves the settings in the dataset (set_adjustment_settings()) and
adjusts it (adjust_data()). The page is then read-only until the person chooses Edit. The page
reads countdown_data, performance_threshold, adjustment_settings, adjusted_flag and
adjusted_data from the dataset.
data_adjustment_ui() returns the page's UI as Shiny tags. data_adjustment_server()
is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_adjustment", ui = data_adjustment_ui, server = data_adjustment_server, title = "title_adjust_main", section = "lbl_nav_section_quality", subtitle = "sub_adjust_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_adjustment", ui = data_adjustment_ui, server = data_adjustment_server, title = "title_adjust_main", section = "lbl_nav_section_quality", subtitle = "sub_adjust_main" ) ## End(Not run)
The data quality page on missing values. Its first card has three tabs: a heat map of completeness by admin level 1 area or district, a chart of district completeness for the chosen indicator, and a line chart of the indicator's completeness over the years. Below it is a table of the units with missing values in the year picked on the table. The filters are the indicator, which can also be set to all indicators, and the admin level with its region. With all indicators chosen, the table lists the missing units of every indicator, with a column that names the indicator.
data_completeness_ui(id, i18n) data_completeness_server(id, cache, i18n, active = reactive(TRUE))data_completeness_ui(id, i18n) data_completeness_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
The page reads completeness_admin1, completeness_district and district_completeness from
the dataset, and calls its list_missing_units(), and its calculate_completeness_summary() and
calculate_district_completeness_summary() when a region is chosen. The heat map's Excel
download writes completeness_national and district_completeness.
data_completeness_ui() returns the page's UI as Shiny tags.
data_completeness_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_completeness", ui = data_completeness_ui, server = data_completeness_server, title = "title_complete_main", section = "lbl_nav_section_quality", subtitle = "sub_complete_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "data_completeness", ui = data_completeness_ui, server = data_completeness_server, title = "title_complete_main", section = "lbl_nav_section_quality", subtitle = "sub_complete_main" ) ## End(Not run)
Shows the result of every data quality check on the loaded dataset as a list of rows, each
marked as passed or as a warning, with an explanation in a tooltip. The checks come from
run_all_quality_checks(). The user enters nothing here and nothing is saved to the dataset.
A button in the card's toolbar downloads every issue found as an Excel workbook
(write_quality_issues()). The step counts as complete when every check of severity
"blocking" has passed (see step_quality_complete()).
data_quality_ui(id, i18n) data_quality_server(id, cache, i18n)data_quality_ui(id, i18n) data_quality_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
The rows are in three parts:
the blocking checks: the file and its sheets (always shown as passed, because the wizard cannot reach this step when the file could not be read), the admin sheet's columns, the required columns, a single country, a recognised country, districts across sheets, district consistency, and missing or invalid months;
the informational checks, which never block: population against reported births, reported live births equal to the population's live births in every month, indicators with no data, and month names written in more than one way;
the mapping checks, which never block: admin level 1 names that do not match the survey or the shapefile.
A row is left out when the check did not run. A dataset loaded already merged (a Stata file, or a saved copy without stored results) only has the checks that run on merged data.
One check is not part of this step: that every indicator the group needs is present. It runs when the user presses Finish, because it reads columns that only exist after the sheets are merged.
data_quality_ui() returns the UI as Shiny tags: a card that holds the list of checks
and the download button. data_quality_server() is called for its side effects and returns
nothing useful.
## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "quality", ui = data_quality_ui(ns("data_quality"), i18n)) data_quality_server("data_quality", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "quality", ui = data_quality_ui(ns("data_quality"), i18n)) data_quality_server("data_quality", cache, i18n) ## End(Not run)
The keys of the tabs on the denominator assessment page (denominator_assessment_ui()): total
population, births and children under one.
den_indicatorsden_indicators
A character vector.
den_indicatorsden_indicators
The page that compares the population figures in the health data (DHIS2) with the United
Nations estimates over the years. One card has three tabs, each with a chart: total population,
births (the DHIS2 live births and total births) and children under one. The one filter is the
population chip (cd_population_ui()), which shows the dataset's derivation_population and
saves a change to it there. The charts read denominator_metrics from the dataset.
denominator_assessment_ui(id, i18n) denominator_assessment_server(id, cache, i18n, active = reactive(TRUE))denominator_assessment_ui(id, i18n) denominator_assessment_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
denominator_assessment_ui() returns the page's UI as Shiny tags.
denominator_assessment_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "denominator_assessment", ui = denominator_assessment_ui, server = denominator_assessment_server, title = "title_denom_assessment", section = "lbl_nav_section_denominators", subtitle = "sub_denom_assessment" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "denominator_assessment", ui = denominator_assessment_ui, server = denominator_assessment_server, title = "title_denom_assessment", section = "lbl_nav_section_denominators", subtitle = "sub_denom_assessment" ) ## End(Not run)
The page where the person compares the candidate denominators and chooses the ones the analysis
uses. It has three cards: coverage from each denominator beside the survey estimate
(survey_comparison_ui()), coverage by admin level 1 area (subnational_denominator_ui()) and
coverage over the years (coverage_trends_ui()). The filters are the denominator for the
vaccination indicators, the denominator for the maternal indicators (only in an app that has
them, see cd_has_maternal()) and the admin level, which includes national, with its region.
The denominator filters are also where the choice is made (cd_denominator_ui()): they show
the dataset's denominator and maternal_denominator, and a change is saved there.
denominator_selection_ui(id, i18n) denominator_selection_server(id, cache, i18n, active = reactive(TRUE))denominator_selection_ui(id, i18n) denominator_selection_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
denominator_selection_ui() returns the page's UI as Shiny tags.
denominator_selection_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "denominator_selection", ui = denominator_selection_ui, server = denominator_selection_server, title = "title_denom_selection", section = "lbl_nav_section_denominators", subtitle = "sub_denom_selection" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "denominator_selection", ui = denominator_selection_ui, server = denominator_selection_server, title = "title_denom_selection", section = "lbl_nav_section_denominators", subtitle = "sub_denom_selection" ) ## End(Not run)
Given a character vector of indicator codes present in the dataset, selects
the group whose entire universe is present in the data (strict coverage:
group ⊆ data). If multiple groups are fully covered, the tie is broken by
choosing the largest universe (most specific), then alphabetically.
detect_indicator_group(indicators)detect_indicator_group(indicators)
indicators |
Character vector of indicator codes present in the data. |
Detection considers the merged view from .get_all_groups() (i.e., built-ins
plus any user overrides registered via register_indicator_group()).
The detected group name (character scalar).
## Not run: inds <- c("anc1","penta1","penta3","measles1","measles2","bcg") detect_indicator_group(inds) ## End(Not run)## Not run: inds <- c("anc1","penta1","penta3","measles1","measles2","bcg") detect_indicator_group(inds) ## End(Not run)
equiplot generates a dot plot to visualize the distribution of variables across
different groups (e.g., countries, regions, or interventions). It is designed for
equity analysis by plotting values for variables like health intervention coverage
across subgroups, allowing insights into disparities.
equiplot( .data, variables, group_by, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, legend_title = NULL, legend_labels = NULL, reverse_y_axis = FALSE, connect_dots = TRUE, dot_size = NULL )equiplot( .data, variables, group_by, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, legend_title = NULL, legend_labels = NULL, reverse_y_axis = FALSE, connect_dots = TRUE, dot_size = NULL )
.data |
A data frame with one row per group and one column per variable (values in percent, plotted on a 0-100 scale). |
variables |
Character vector of the column names to plot as dots; each becomes a coloured series. |
group_by |
The column (unquoted or as a string) whose values form the rows of the plot (y axis). |
title, subtitle, caption
|
Optional plot title, subtitle and caption.
Each must be a single string or |
x_title |
Optional x-axis title. Defaults to a percentage label. |
legend_title |
Optional title of the colour legend. |
legend_labels |
Optional named vector or list mapping variable names to display labels (for example translated labels). |
reverse_y_axis |
Logical. Whether to reverse the order of the groups on
the y axis. Default is |
connect_dots |
Logical. Whether to draw a line connecting the dots of
each group. Default is |
dot_size |
Optional dot size, clamped to 1-5. Defaults to 4. |
A ggplot object.
coverage <- data.frame( region = c("North", "Centre", "South"), poorest = c(42, 55, 61), richest = c(78, 83, 90) ) equiplot(coverage, variables = c("poorest", "richest"), group_by = region) equiplot(coverage, c("poorest", "richest"), group_by = region, title = "Skilled birth attendance by wealth", legend_title = "Wealth quintile", legend_labels = c(poorest = "Poorest", richest = "Richest"), connect_dots = FALSE)coverage <- data.frame( region = c("North", "Centre", "South"), poorest = c(42, 55, 61), richest = c(78, 83, 90) ) equiplot(coverage, variables = c("poorest", "richest"), group_by = region) equiplot(coverage, c("poorest", "richest"), group_by = region, title = "Skilled birth attendance by wealth", legend_title = "Wealth quintile", legend_labels = c(poorest = "Poorest", richest = "Richest"), connect_dots = FALSE)
Plots rural and urban survey estimates of an indicator by year.
equiplot_area( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )equiplot_area( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
.data |
Equity survey data with |
indicator |
Character. The indicator to plot; its |
dot_size |
Optional dot size, clamped to 1-5. Defaults to 4. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional named vector or list mapping group names to display labels. |
options |
A |
A ggplot object: the dot plot drawn by equiplot(), with one row per survey year and one
dot each for rural and urban, and the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by residence equiplot_area(cache$area_survey, "anc4") equiplot_area(cache$area_survey, "anc4", title = "Four antenatal visits by residence", legend_title = "Residence", legend_labels = list(Rural = "Rural areas", Urban = "Towns"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by residence equiplot_area(cache$area_survey, "anc4") equiplot_area(cache$area_survey, "anc4", title = "Four antenatal visits by residence", legend_title = "Residence", legend_labels = list(Rural = "Rural areas", Urban = "Towns"))
Plots survey estimates of an indicator by year for each level of maternal education.
equiplot_education( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )equiplot_education( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
.data |
Equity survey data with |
indicator |
Character. The indicator to plot; its |
dot_size |
Optional dot size, clamped to 1-5. Defaults to 4. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional named vector or list mapping group names to display labels. |
options |
A |
A ggplot object: the dot plot drawn by equiplot(), with one row per survey year and one
dot for each level of maternal education, and the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by maternal education equiplot_education(cache$education_survey, "penta3") equiplot_education(cache$education_survey, "penta3", title = "Penta3 by education of the mother", x_title = "Penta3 coverage (%)", dot_size = 3, legend_position = "bottom")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by maternal education equiplot_education(cache$education_survey, "penta3") equiplot_education(cache$education_survey, "penta3", title = "Penta3 by education of the mother", x_title = "Penta3 coverage (%)", dot_size = 3, legend_position = "bottom")
Plots survey estimates of an indicator by year for each wealth quintile.
equiplot_wealth( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )equiplot_wealth( .data, indicator, dot_size = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
.data |
Equity survey data with |
indicator |
Character. The indicator to plot; its |
dot_size |
Optional dot size, clamped to 1-5. Defaults to 4. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional named vector or list mapping group names to display labels. |
options |
A |
A ggplot object: the dot plot drawn by equiplot(), with one row per survey year and one
dot for each wealth quintile (Q1 to Q5), and the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by wealth quintile equiplot_wealth(cache$wiq_survey, "instlivebirths") equiplot_wealth(cache$wiq_survey, "instlivebirths", title = "Institutional live births by wealth", legend_title = "Quintile", caption = "Source: household surveys")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the dataset object gives the package's survey estimates for the country, by wealth quintile equiplot_wealth(cache$wiq_survey, "instlivebirths") equiplot_wealth(cache$wiq_survey, "instlivebirths", title = "Institutional live births by wealth", legend_title = "Quintile", caption = "Source: household surveys")
Shows how survey coverage of an indicator differs between groups of the population, as an
equiplot for each survey. One filter chooses the grouping: place of residence (urban and rural),
mother's education or wealth quintile; the page reads the matching survey table of the dataset
(cache()$area_survey, cache()$education_survey or cache()$wiq_survey). The charts sit in
one card with a tab for each indicator the app lists (cd_cfg("equity_indicators")) and a Custom
tab, where any analysis indicator can be picked except those in
cd_cfg("equity_custom_exclude").
equity_ui(id, i18n) equity_server(id, cache, i18n, active = reactive(TRUE))equity_ui(id, i18n) equity_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
equity_ui() returns the page's UI as Shiny tags. equity_server() returns a reactive
that holds the key of the tab shown: an indicator's name, or "custom".
## Not run: # the page's entry in an app's page registry cd_page_def( id = "equity_assessment", ui = equity_ui, server = equity_server, title = "title_nav_equity", section = "title_nav_national_analysis", subtitle = "sub_equity" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "equity_assessment", ui = equity_ui, server = equity_server, title = "title_nav_equity", section = "title_nav_national_analysis", subtitle = "sub_equity" ) ## End(Not run)
Filters a dataset to retain administrative areas with coverage values above a specified threshold for a given indicator and denominator.
filter_high_performers( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), threshold = 90 )filter_high_performers( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), threshold = 90 )
.data |
An object of class |
indicator |
A string specifying the indicator. |
denominator |
A string. The denominator used in coverage calculation. |
threshold |
Numeric. Minimum coverage (in percent, compared after
rounding) an area must reach to be kept. Default is |
A filtered data frame retaining regions meeting the threshold.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$indicator_coverage_admin1 filter_high_performers(coverage, indicator = "instlivebirths", denominator = "dhis2") filter_high_performers(coverage, indicator = "instlivebirths", denominator = "dhis2", threshold = 100)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$indicator_coverage_admin1 filter_high_performers(coverage, indicator = "instlivebirths", denominator = "dhis2") filter_high_performers(coverage, indicator = "instlivebirths", denominator = "dhis2", threshold = 100)
The filter_out_years function is used to exclude specified years from a DHIS-2
dataset, refining the data for more targeted analysis or reporting. This is
particularly useful when focusing on specific timeframes, such as recent years
only or a custom-defined analysis period. By removing data from unwanted years,
you can create a tailored dataset aligned with analytical goals.
filter_out_years(.data, years_to_exclude)filter_out_years(.data, years_to_exclude)
.data |
A |
years_to_exclude |
An integer vector that specifies the years to exclude from the dataset. |
Purpose: Use this function when specific years are unnecessary for analysis, such as baseline years or years with incomplete data.
Validation:
Ensures .data is a valid cd_data object for DHIS-2 analysis.
Confirms years_to_exclude is a vector of integers; raises an error if
not properly specified.
Functionality: Filters .data to retain only the rows where the year
does not match any value in years_to_exclude.
A cd_data object with rows filtered to exclude those matching
the specified years in years_to_exclude. The resulting data set is intended
for focused analysis across the remaining years.
## Not run: # Example: Remove data for 2017 and 2018 from a DHIS-2 dataset filtered_data <- filter_out_years(dhis_data, years_to_exclude = c(2017, 2018)) ## End(Not run)## Not run: # Example: Remove data for 2017 and 2018 from a DHIS-2 dataset filtered_data <- filter_out_years(dhis_data, years_to_exclude = c(2017, 2018)) ## End(Not run)
generate_adjustment_values calculates yearly unadjusted and adjusted service counts
for each indicator within a cd_data dataset, applying the specified adjustment type.
It provides a comparison of raw and adjusted values for analysis purposes.
generate_adjustment_values( .data, adjustment = c("default", "custom", "none"), k_factors = NULL, settings = NULL, area = NULL, level = c("adminlevel_1", "district") )generate_adjustment_values( .data, adjustment = c("default", "custom", "none"), k_factors = NULL, settings = NULL, area = NULL, level = c("adminlevel_1", "district") )
.data |
A |
adjustment |
A character string specifying the adjustment type:
|
k_factors |
A named numeric vector of custom k-factor values between 0 and 1 for
each indicator group (e.g., |
settings |
The adjustment settings ( |
area, level
|
One area only: a region ( |
Performs the following steps:
Data Validation: Ensures .data is of the cd_data class and adjustment
is correctly specified.
Unadjusted Summation: Calculates the yearly sums of unadjusted service counts.
Adjusted Summation: Applies adjust_service_data() to compute adjusted values,
then calculates the yearly sums.
Combining Results: Merges unadjusted and adjusted yearly counts for comparison.
A cd_adjustment_values tibble containing:
Columns for unadjusted values, suffixed with _raw.
Columns for adjusted values, suffixed with _adj.
A year column indicating the year of each count.
adjust_service_data() for the detailed adjustment function.
## Not run: # Generate adjustment values with default k-factors adjustment_values_default <- generate_adjustment_values(data, adjustment = "default") # Generate adjustment values with custom k-factors custom_k <- c(anc = 0.3, idelv = 0.2, pnc = 0.35, vacc = 0.4, opd = 0.3, ipd = 0.25) adjustment_values_custom <- generate_adjustment_values(data, adjustment = "custom", k_factors = custom_k) # Generate unadjusted values only unadjusted_values <- generate_adjustment_values(data, adjustment = "none") ## End(Not run)## Not run: # Generate adjustment values with default k-factors adjustment_values_default <- generate_adjustment_values(data, adjustment = "default") # Generate adjustment values with custom k-factors custom_k <- c(anc = 0.3, idelv = 0.2, pnc = 0.35, vacc = 0.4, opd = 0.3, ipd = 0.25) adjustment_values_custom <- generate_adjustment_values(data, adjustment = "custom", k_factors = custom_k) # Generate unadjusted values only unadjusted_values <- generate_adjustment_values(data, adjustment = "none") ## End(Not run)
Gives each distinct admin level 1 name a short key, so that the same unit can be identified in several tables (for example the dataset, the survey mapping and the map mapping). Generate the keys once from the dataset's names, then join them to the other tables by name.
generate_admin1_keys(admin1_names)generate_admin1_keys(admin1_names)
admin1_names |
A character vector of admin level 1 names, usually the |
The keys are arbitrary: the distinct names are sorted and numbered in that order. They are not standard codes, and they are not stable between datasets. A dataset with a different set of names can give a different key to the same unit. Missing names get no key.
A tibble with one row per distinct name, sorted by name, and columns adminlevel_1
(the name) and admin1_key (the key: "A1-001", "A1-002" and so on).
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) generate_admin1_keys(data$adminlevel_1) # Repeated and missing names get no key of their own generate_admin1_keys(c("Western", "Coast", "Western", NA))path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) generate_admin1_keys(data$adminlevel_1) # Repeated and missing names get no key of their own generate_admin1_keys(c("Western", "Coast", "Western", NA))
Keeps the latest year of subnational service utilization data and its two service indices: the
MCH preventive services index and the curative services index. The result is ready for
plot.cd_mch_curative_index().
generate_admin1_mch_curative_index(service_utilization)generate_admin1_mch_curative_index(service_utilization)
service_utilization |
Dataframe containing admin level 1 service utilization. |
A tibble with class cd_mch_curative_index.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) utilization <- compute_service_utilization(data, admin_level = "adminlevel_1") index <- generate_admin1_mch_curative_index(utilization) index plot(index)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) utilization <- compute_service_utilization(data, admin_level = "adminlevel_1") index <- generate_admin1_mch_curative_index(utilization) index plot(index)
Keeps the latest year of subnational service utilization data and the under-five utilization
rate of one service: OPD visits per child (ratio_opd_u5_pop) or IPD admissions per 100
children (ratio_ipd_u5_pop). The result is ready for plot.cd_service_utilization_admin1().
generate_admin1_service_utilization( service_utilization, metric_type = c("opd", "ipd") )generate_admin1_service_utilization( service_utilization, metric_type = c("opd", "ipd") )
service_utilization |
Dataframe containing admin level 1 service utilization. |
metric_type |
Character. Either "opd" or "ipd". |
A tibble with class cd_service_utilization_admin1 and the columns adminlevel_1, year
and the selected rate. The attribute metric_type holds metric_type.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) utilization <- compute_service_utilization(data, admin_level = "adminlevel_1") # outpatient visits per child under five, by region, in the latest year generate_admin1_service_utilization(utilization, metric_type = "opd") # inpatient admissions per 100 children under five admissions <- generate_admin1_service_utilization(utilization, metric_type = "ipd") plot(admissions)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) utilization <- compute_service_utilization(data, admin_level = "adminlevel_1") # outpatient visits per child under five, by region, in the latest year generate_admin1_service_utilization(utilization, metric_type = "opd") # inpatient admissions per 100 children under five admissions <- generate_admin1_service_utilization(utilization, metric_type = "ipd") plot(admissions)
Fits a Bayesian coverage model for one indicator, combining the survey estimates and the routine
(DHIS2) coverage in coverage_data with the yearly data quality score in overall_score. The
model is national or sub-national (admin level 1), following the admin level of coverage_data.
generate_bayes_model( coverage_data, overall_score, indicator = c("anc4", "anc_1trimester", "ideliv", "measles1", "penta3"), denominator = c("anc1", "dhis2", "penta1", "penta1derived", "anc1derived"), keep_samples = FALSE )generate_bayes_model( coverage_data, overall_score, indicator = c("anc4", "anc_1trimester", "ideliv", "measles1", "penta3"), denominator = c("anc1", "dhis2", "penta1", "penta1derived", "anc1derived"), keep_samples = FALSE )
coverage_data |
Survey data frame of class 'cd_coverage'. |
overall_score |
DHIS2 data frame of class 'cd_overall_score'. |
indicator |
Indicator character code (e.g., 'anc4', 'penta3'). |
denominator |
The denominator type to use from DHIS2 (e.g., 'penta1', 'dhis2'). |
keep_samples |
Whether the model keeps the sampler's draws and the compiled Stan model ( |
An object of class cd_bayes_model: the fitted model returned by
bayescoveragedeploy::fit_local_model() (a list, with its posteriors summary), without samples and
stan_model unless keep_samples = TRUE. It carries the attributes indicator, model_indicator (the
name the model uses for the indicator), iso and is_national.
## Not run: # needs the Bayesian model packages (see cd_bayes_packages_missing()); a fit takes minutes path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() model <- generate_bayes_model( coverage_data = cache$calculate_coverage("national"), overall_score = cache$overall_score, indicator = "penta3", denominator = "penta1" ) bayes_model_estimates(model) plot(model) ## End(Not run)## Not run: # needs the Bayesian model packages (see cd_bayes_packages_missing()); a fit takes minutes path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() model <- generate_bayes_model( coverage_data = cache$calculate_coverage("national"), overall_score = cache$overall_score, indicator = "penta3", denominator = "penta1" ) bayes_model_estimates(model) plot(model) ## End(Not run)
Processes and shapes raw coverage data into a clean, long format optimized for continuum-of-care plotting. It dynamically builds regex patterns based on the spatial level and data type to extract relevant columns:
National: Extracts Facility, Survey, and WUENIC data.
Subnational: Extracts Facility data only.
The function automatically filters for the absolute latest available data point
per indicator-source combination and converts the indicator column into an
ordered factor representing the lifecycle stages to ensure plots are always ordered correctly.
generate_coverage_data( .data, type = c("maternal", "child"), denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived") )generate_coverage_data( .data, type = c("maternal", "child"), denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived") )
.data |
A data frame/tibble originating from |
type |
Character. Specifies whether to extract 'maternal' or 'child' indicators. |
denominator |
Character. The denominator to use for the specified indicator type. Options include "dhis2", "anc1", "penta1", "penta1derived", or "anc1derived". |
A tibble of class cd_coverage_selected containing the latest
coverage values, categorized sources, and ordered indicators. Retains
admin_level and admin_col attributes for downstream plotting.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$calculate_coverage("national") generate_coverage_data(coverage, type = "maternal", denominator = "anc1") generate_coverage_data(coverage, type = "child", denominator = "penta1")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$calculate_coverage("national") generate_coverage_data(coverage, type = "maternal", denominator = "anc1") generate_coverage_data(coverage, type = "child", denominator = "penta1")
Processes raw FPET data (e.g., from Track20 or UNFPA) into a structured tibble for visualization and interpretation of modern contraceptive prevalence and demand satisfied.
generate_fpet_summary(.data)generate_fpet_summary(.data)
.data |
An object of class |
A cd_fpet_data object.
## Not run: # an FPET results file (.csv) for the country fpet <- load_fpet_data(path = "fpet_kenya.csv", country_iso = "KEN") summary <- generate_fpet_summary(fpet) plot(summary) interpret(summary) ## End(Not run)## Not run: # an FPET results file (.csv) for the country fpet <- load_fpet_data(path = "fpet_kenya.csv", country_iso = "KEN") summary <- generate_fpet_summary(fpet) plot(summary) interpret(summary) ## End(Not run)
Arranges national health system metrics as a table of eight indicators in three sections: health
infrastructure, health workforce and the role of the private sector. Each row has the indicator's
label, its value and its unit, ready for plot.cd_health_system_table().
generate_health_system_table(metric_data, labels = NULL)generate_health_system_table(metric_data, labels = NULL)
metric_data |
A |
labels |
(Optional) A nested list of localized labels for sections, indicators, and units
(elements |
A tibble of class cd_health_system_table with one row per indicator and the columns
section, indicator, value and unit (NA where the indicator has no unit).
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "national") generate_health_system_table(metrics) # labels in another language: what is not given stays in English generate_health_system_table(metrics, labels = list(section = list(workforce = "Personnel de sante")))path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "national") generate_health_system_table(metrics) # labels in another language: what is not given stays in English generate_health_system_table(metrics, labels = list(section = list(workforce = "Personnel de sante")))
Pairs a health system input (facility density or health workforce density) with a service
coverage index for each admin level 1 unit, for plot.cd_phc_scatter(). The service coverage
index is the mean of the MCH preventive services index and the curative services index.
generate_phc_scatter_data( .data, x_indicator = c("ratio_fac_pop", "ratio_hstaff_pop") )generate_phc_scatter_data( .data, x_indicator = c("ratio_fac_pop", "ratio_hstaff_pop") )
.data |
A |
x_indicator |
Independent variable ('ratio_fac_pop' or 'ratio_hstaff_pop'). |
A tibble of class cd_phc_scatter with one row per admin level 1 unit and the columns
adminlevel_1, the column named by x_indicator, service_coverage and is_outlier (TRUE
when service_coverage is below the first quartile or above the third quartile). The
attribute indicator holds x_indicator.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") generate_phc_scatter_data(metrics, x_indicator = "ratio_fac_pop") # against the density of health workers workforce <- generate_phc_scatter_data(metrics, x_indicator = "ratio_hstaff_pop") plot(workforce)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") generate_phc_scatter_data(metrics, x_indicator = "ratio_fac_pop") # against the density of health workers workforce <- generate_phc_scatter_data(metrics, x_indicator = "ratio_hstaff_pop") plot(workforce)
Reshapes health system metrics into the share of health facilities that are private, NGO and
public in each admin level 1 unit, for plot.cd_private_sector(). The public share is what
remains after the private and NGO shares.
generate_private_sector_data(.data, legend_labels = NULL)generate_private_sector_data(.data, legend_labels = NULL)
.data |
Data frame containing subnational health indicators, with the columns
|
legend_labels |
(Optional) A named list to override default legend labels (elements
|
A tibble of class cd_private_sector with one row per admin level 1 unit and facility
type, and the columns adminlevel_1, facility_type (a factor ordered private, NGO, public,
with the labels as its levels) and share (percent). The attributes lbl_prv, lbl_ngo and
lbl_pub hold the labels used.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") generate_private_sector_data(metrics) # with another label in the legend shares <- generate_private_sector_data(metrics, legend_labels = list(Private = "For profit")) plot(shares)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) metrics <- calculate_health_system_metrics(data, admin_level = "adminlevel_1") generate_private_sector_data(metrics) # with another label in the legend shares <- generate_private_sector_data(metrics, legend_labels = list(Private = "For profit")) plot(shares)
Combines the reporting rate, completeness, outlier and service utilization results for
outpatient (OPD) and inpatient (IPD) services into one data quality table, with a row per
indicator and a column per year. The rows are numbered and grouped under three section headers,
ready for plot.cd_utilization_dqa().
generate_service_dqa_summary( average_reporting_rate, district_reporting_rate, completeness_national, district_completeness, outliers_summary, district_outliers_summary, service_utilization, threshold = .cd_method$data_quality$reporting_threshold, labels = NULL )generate_service_dqa_summary( average_reporting_rate, district_reporting_rate, completeness_national, district_completeness, outliers_summary, district_outliers_summary, service_utilization, threshold = .cd_method$data_quality$reporting_threshold, labels = NULL )
average_reporting_rate |
Dataframe. Reporting rate data. |
district_reporting_rate |
Dataframe. District reporting rate data. |
completeness_national |
Dataframe. National completeness data. |
district_completeness |
Dataframe. District completeness data. |
outliers_summary |
Dataframe. National outliers data. |
district_outliers_summary |
Dataframe. District outliers summary data. |
service_utilization |
Dataframe. Output of compute_service_utilization('national'). |
threshold |
Numeric. The performance threshold (in percent) shown in the label. Default is |
labels |
List. Optional custom labels for sections and indicators. |
A wide-format tibble with summarized DQA indicators grouped by section.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) generate_service_dqa_summary( average_reporting_rate = calculate_average_reporting_rate(data), district_reporting_rate = calculate_district_reporting_rate(data), completeness_national = calculate_completeness_summary(data), district_completeness = calculate_district_completeness_summary(data), outliers_summary = calculate_outliers_summary(data), district_outliers_summary = calculate_district_outlier_summary(data), service_utilization = compute_service_utilization(data, admin_level = "national") )path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) generate_service_dqa_summary( average_reporting_rate = calculate_average_reporting_rate(data), district_reporting_rate = calculate_district_reporting_rate(data), completeness_national = calculate_completeness_summary(data), district_completeness = calculate_district_completeness_summary(data), outliers_summary = calculate_outliers_summary(data), district_outliers_summary = calculate_district_outlier_summary(data), service_utilization = compute_service_utilization(data, admin_level = "national") )
Returns the appropriate grouping column(s) based on the specified administrative level.
If a region is specified and admin_level = "adminlevel_1", districts are included to allow
further disaggregation within that region.
get_admin_columns(admin_level, region = NULL, show_district = TRUE)get_admin_columns(admin_level, region = NULL, show_district = TRUE)
admin_level |
A string. One of |
region |
Optional. If provided, must be used only with |
show_district |
Optional. If show_district is true |
A character vector of column names to use in grouping. Returns:
NULL for "national"
"adminlevel_1" or c("adminlevel_1", "district") for "adminlevel_1"
c("adminlevel_1", "district") for "district"
get_admin_columns("national") #> NULL get_admin_columns("adminlevel_1") #> "adminlevel_1" get_admin_columns("adminlevel_1", region = "Eastern") #> c("adminlevel_1", "district") get_admin_columns("district") #> c("adminlevel_1", "district")get_admin_columns("national") #> NULL get_admin_columns("adminlevel_1") #> "adminlevel_1" get_admin_columns("adminlevel_1", region = "Eastern") #> c("adminlevel_1", "district") get_admin_columns("district") #> c("adminlevel_1", "district")
Flatten all indicators from all groups
get_all_indicators()get_all_indicators()
Character vector of all indicators
get_all_indicators() # the indicators of another group (the selected group is put back afterwards) old <- get_selected_group() set_selected_group("vaccine") get_all_indicators() set_selected_group(old)get_all_indicators() # the indicators of another group (the selected group is put back afterwards) old <- get_selected_group() set_selected_group("vaccine") get_all_indicators() set_selected_group(old)
Flatten all indicators from all groups
get_analysis_indicators()get_analysis_indicators()
Character vector of all indicators
get_analysis_indicators() # what the selected group has and the analysis leaves out setdiff(get_all_indicators(), get_analysis_indicators())get_analysis_indicators() # what the selected group has and the analysis leaves out setdiff(get_all_indicators(), get_analysis_indicators())
Reads the ISO3 code of the country a Countdown dataset is for. The code is stored with the data when it is loaded.
get_country_iso3(.data)get_country_iso3(.data)
.data |
A |
The ISO3 country code as a character string
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) get_country_iso3(data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) get_country_iso3(data)
Reads the name of the country a Countdown dataset is for. The name is stored with the data when it is loaded.
get_country_name(.data)get_country_name(.data)
.data |
A |
The country name as a character string
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) get_country_name(data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) get_country_name(data)
Loads the admin level 1 boundaries of a country from the shapefiles that come with the package. Ensures geometries are valid and standardized to WGS84 (EPSG:4326).
get_country_shapefile(country_iso, level = c("admin_level_1", "district"))get_country_shapefile(country_iso, level = c("admin_level_1", "district"))
country_iso |
A string with the ISO3 code of the country (e.g., |
level |
A character string specifying the admin level: |
An sf object containing valid geometries of the country's admin level 1 areas.
shapefile <- get_country_shapefile("KEN", level = "admin_level_1")shapefile <- get_country_shapefile("KEN", level = "admin_level_1")
Flatten all indicators from all groups
get_coverage_indicators()get_coverage_indicators()
Character vector of all indicators
get_coverage_indicators() # the vaccine group calculates coverage for every indicator it has old <- get_selected_group() set_selected_group("vaccine") setequal(get_coverage_indicators(), get_all_indicators()) set_selected_group(old)get_coverage_indicators() # the vaccine group calculates coverage for every indicator it has old <- get_selected_group() set_selected_group("vaccine") setequal(get_coverage_indicators(), get_all_indicators()) set_selected_group(old)
Transforms a cd_service_utilization object into a wide-format table
with labeled indicators, suitable for export to Excel.
get_excel_version(.data)get_excel_version(.data)
.data |
A |
The output table includes population, OPD/IPD service utilization, under-5 service metrics, reporting completeness, and case fatality rates, reshaped to facilitate Excel review or reporting.
A tibble in wide format with:
One row per indicator per admin unit
One column per year
A human-readable label for each indicator (indiclabel)
## Not run: x <- compute_service_utilization(dat, admin_level = "adminlevel_1") get_excel_version(x) ## End(Not run)## Not run: x <- compute_service_utilization(dat, admin_level = "adminlevel_1") get_excel_version(x) ## End(Not run)
Lists the names of the categories (such as anc, idelv or vacc) that the indicators of the
selected indicator group are arranged in. These are the names of get_indicator_groups().
get_indicator_group_names()get_indicator_group_names()
Character vector of indicator group names
get_indicator_group_names() # the indicators of one of them get_indicator_groups()[["vacc"]]get_indicator_group_names() # the indicators of one of them get_indicator_groups()[["vacc"]]
Returns the merged definition for a group (built-in overlaid with any
override). If group is omitted, uses get_selected_group().
get_indicator_groups(group = get_selected_group())get_indicator_groups(group = get_selected_group())
group |
Group name. Defaults to the globally selected group. |
A named list of categories -> character vector of indicators.
get_indicator_groups("rmncah")get_indicator_groups("rmncah")
Merges coverage data with a country's shapefile to enable spatial visualization of health indicators. It joins subnational (admin level 1) indicator coverage that has already been calculated with the geographic features of each unit.
get_mapping_data(.data, subnational_map = NULL)get_mapping_data(.data, subnational_map = NULL)
.data |
A |
subnational_map |
Optional. A data frame to join with the shapefile to add metadata. |
A tibble of class "cd_mapping" that combines the input data with shapefile geometries.
## Not run: coverage <- calculate_indicator_coverage(data, admin_level = "adminlevel_1") get_mapping_data(coverage) ## End(Not run)## Not run: coverage <- calculate_indicator_coverage(data, admin_level = "adminlevel_1") get_mapping_data(coverage) ## End(Not run)
Each indicator is named by its group
get_named_indicators()get_named_indicators()
Named character vector of indicators
indicators <- get_named_indicators() head(indicators) # the indicators of one category unname(indicators[names(indicators) == "vacc"])indicators <- get_named_indicators() head(indicators) # the indicators of one category unname(indicators[names(indicators) == "vacc"])
Takes the most recent survey value of ANC1 coverage, Penta1 coverage and the stillbirth,
neonatal and post-neonatal mortality rates, and converts each to a proportion. A rate the
survey data does not have is filled with the value given in the matching argument. The result
has the rates that calculate_indicator_coverage() takes as arguments.
get_national_rates( .data, admin_level = c("national", "adminlevel_1", "district"), anc1survey = .cd_method$denominators$anc1survey, dpt1survey = .cd_method$denominators$dpt1survey, sbr = .cd_method$denominators$sbr, nmr = .cd_method$denominators$nmr, pnmr = .cd_method$denominators$pnmr, twin = .cd_method$denominators$twin, preg_loss = .cd_method$denominators$preg_loss, subnational_map = NULL )get_national_rates( .data, admin_level = c("national", "adminlevel_1", "district"), anc1survey = .cd_method$denominators$anc1survey, dpt1survey = .cd_method$denominators$dpt1survey, sbr = .cd_method$denominators$sbr, nmr = .cd_method$denominators$nmr, pnmr = .cd_method$denominators$pnmr, twin = .cd_method$denominators$twin, preg_loss = .cd_method$denominators$preg_loss, subnational_map = NULL )
.data |
A |
admin_level |
Character. The administrative level of the survey data: |
anc1survey |
Numeric. ANC1 coverage (a proportion) to use where the survey has no value. |
dpt1survey |
Numeric. Penta1 coverage (a proportion) to use where the survey has no value. |
sbr |
Numeric. Stillbirth rate (a proportion) to use where the survey has no value. |
nmr |
Numeric. Neonatal mortality rate (a proportion) to use where the survey has no value. |
pnmr |
Numeric. Post-neonatal mortality rate (a proportion) to use where the survey has no value. |
twin |
Numeric. Twin birth rate (a proportion). It is not read from the survey data, so this value is always the one returned. |
preg_loss |
Numeric. Pregnancy loss rate (a proportion). It is not read from the survey data, so this value is always the one returned. |
subnational_map |
Optional. A data frame mapping survey regions to |
A tibble with one row for national data, or one row per unit for subnational data,
and the columns pnmr, nmr, sbr, preg_loss, twin, anc1survey and dpt1survey, all
as proportions. Subnational results also have the admin column or columns.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) rates <- get_national_rates(cache$national_survey) rates # A stillbirth rate of your own, used because the survey has none get_national_rates(cache$national_survey, sbr = 0.015)$sbr # The rates of each survey region regional <- get_national_rates(cache$regional_survey, admin_level = "adminlevel_1") regionalpath <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) rates <- get_national_rates(cache$national_survey) rates # A stillbirth rate of your own, used because the survey has none get_national_rates(cache$national_survey, sbr = 0.015)$sbr # The rates of each survey region regional <- get_national_rates(cache$regional_survey, admin_level = "adminlevel_1") regional
Returns the appropriate administrative unit column to use on plots based on the selected administrative level and whether a region is specified. Used to decide whether to facet or label plots by district or by adminlevel_1.
get_plot_admin_column(admin_level, region = NULL)get_plot_admin_column(admin_level, region = NULL)
admin_level |
A string. Either |
region |
Optional. A region name or |
A string: either "district" or "adminlevel_1".
get_plot_admin_column("adminlevel_1") #> "adminlevel_1" get_plot_admin_column("adminlevel_1", region = "Nairobi") #> "district" get_plot_admin_column("district") #> "district"get_plot_admin_column("adminlevel_1") #> "adminlevel_1" get_plot_admin_column("adminlevel_1", region = "Nairobi") #> "district" get_plot_admin_column("district") #> "district"
Names the column that holds the target population of an indicator for a denominator option. The
name is the indicator's target population followed by the denominator, for example
"totinftpenta_penta1" for penta3 with the penta1 denominator.
get_population_column(indicator, denominator)get_population_column(indicator, denominator)
indicator |
Character scalar. Indicator name (e.g., 'penta1', 'measles1') |
denominator |
Character scalar. The denominator for the indicator: one of |
A string naming the corresponding population column, or NA when the indicator has no
target population defined.
get_population_column("penta3", "penta1") get_population_column("anc4", "dhis2") # births are total births with the DHIS2 denominator, live births with the others get_population_column("bcg", "dhis2") get_population_column("bcg", "anc1")get_population_column("penta3", "penta1") get_population_column("anc4", "dhis2") # births are total births with the DHIS2 denominator, live births with the others get_population_column("bcg", "dhis2") get_population_column("bcg", "anc1")
Returns the last group set via set_selected_group(). If none is set for the
session, falls back to getOption("cd2030.selected_group", "rmncah") and caches it.
get_selected_group()get_selected_group()
A length-1 character vector (group name).
get_selected_group()get_selected_group()
The body of the inequality pages: one card of charts with a tab for each of the app's default
indicators (cd_default_indicator_set()) and a Custom tab for any other analysis indicator. A
tab plots, by year, the coverage of every sub-national unit beside the reference coverage held in
the inequality table, with the denominator selected for the indicator. It reads the dataset's
get_filtered_inequality(): cache()$inequality_admin1 for admin level 1 with no region, and
cache()$inequality_district otherwise, limited to the region's districts when a region is
given. Both tables measure units against the national value; when a region is given the legend
names the reference after the region. The piece has no filters of its own: the page gives it the
admin level and region.
inequality_ui(id, i18n, title_key = "title_inequ_national") inequality_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )inequality_ui(id, i18n, title_key = "title_inequ_national") inequality_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
title_key |
The translation key of the card's title. By default the national page's. |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A reactive that returns the level of the units compared: |
region |
A reactive that returns the name of an admin level 1 region, to compare its
districts, or |
active |
A reactive that is |
inequality_ui() returns the card's UI as Shiny tags. inequality_server() returns a
reactive that holds the key of the tab shown: an indicator's name, or "custom". The national
inequality page uses it to show the same tab on its maps.
## Not run: # the charts in a page module, for the admin level 1 areas of the country my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, inequality_ui(ns("inequality"), i18n, title_key = "title_inequ_national")) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { shown <- inequality_server("inequality", cache, i18n, reactive("adminlevel_1"), active = active) observe(message("Tab shown: ", shown())) }) } ## End(Not run)## Not run: # the charts in a page module, for the admin level 1 areas of the country my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, inequality_ui(ns("inequality"), i18n, title_key = "title_inequ_national")) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { shown <- inequality_server("inequality", cache, i18n, reactive("adminlevel_1"), active = active) observe(message("Tab shown: ", shown())) }) } ## End(Not run)
init_CacheConnection initializes a CacheConnection either from a provided .rds file path
or directly from a cd_data object. Only one of the arguments should be non-NULL.
init_CacheConnection( rds_path = NULL, countdown_data = NULL, data_path = NULL, wizard_parts = NULL, indicator_group = c("auto", "rmncah", "vaccine", "custom"), read_only = FALSE )init_CacheConnection( rds_path = NULL, countdown_data = NULL, data_path = NULL, wizard_parts = NULL, indicator_group = c("auto", "rmncah", "vaccine", "custom"), read_only = FALSE )
rds_path |
Optional character. Path to an RDS file to load the cache from. |
countdown_data |
Optional |
data_path |
Optional character. Path to the original source file
(e.g. the |
wizard_parts |
Optional |
indicator_group |
Character. Specifies the indicator group to use (auto, rmncah, vaccine, custom). |
read_only |
Logical. |
An instance of the CacheConnection class.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) # in memory: no file is written cache <- init_CacheConnection(countdown_data = data) cache$country cache$data_years ## Not run: # the dataset an app saved, opened without ever writing to it cache <- init_CacheConnection(rds_path = "kenya_rmncah.rds", read_only = TRUE) ## End(Not run)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) # in memory: no file is written cache <- init_CacheConnection(countdown_data = data) cache$country cache$data_years ## Not run: # the dataset an app saved, opened without ever writing to it cache <- init_CacheConnection(rds_path = "kenya_rmncah.rds", read_only = TRUE) ## End(Not run)
The data quality page on how well related indicators agree with each other. It has two cards
and no filters: the ratio chart (calculate_ratios_ui()) and the consistency checks, which
compare pairs of indicators (consistency_check_ui()). Those two pieces read ratios_summary
and countdown_data from the dataset.
internal_consistency_ui(id, i18n) internal_consistency_server(id, cache, i18n, active = reactive(TRUE))internal_consistency_ui(id, i18n) internal_consistency_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
internal_consistency_ui() returns the page's UI as Shiny tags.
internal_consistency_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "internal_consistency", ui = internal_consistency_ui, server = internal_consistency_server, title = "title_consist_main", section = "lbl_nav_section_quality", subtitle = "sub_consist_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "internal_consistency", ui = internal_consistency_ui, server = internal_consistency_server, title = "title_consist_main", section = "lbl_nav_section_quality", subtitle = "sub_consist_main" ) ## End(Not run)
A generic method to extract narrative interpretation from structured data objects.
interpret(x, ...)interpret(x, ...)
x |
An object. |
... |
Additional arguments passed to methods. |
What the method for the class of x returns. The method for cd_fpet_data
(interpret.cd_fpet_data()) returns a character string.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # the family planning estimates that come with the dataset interpret(cache$fpet_data)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) # the family planning estimates that come with the dataset interpret(cache$fpet_data)
Summarizes 2020 and 2024 estimates, and briefly mentions FPET projections to 2030.
## S3 method for class 'cd_fpet_data' interpret(x, ...)## S3 method for class 'cd_fpet_data' interpret(x, ...)
x |
A |
... |
Unused. |
A character string with interpretation summary.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) text <- interpret(cache$fpet_data) cat(text)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) text <- interpret(cache$fpet_data) cat(text)
The app's opening screen: one card that shows the app's introduction text in the chosen
language. The text is the Markdown file 0_intro_<language>.md in the app's help folder, which
an app sets with options(cd2030.help_dir = ) (by default "help"). When there is no file for
the language, the English one (0_intro_en.md) is shown. The page reads nothing from the
dataset.
introduction_ui(id, i18n) introduction_server(id, selected_language)introduction_ui(id, i18n) introduction_server(id, selected_language)
id |
The module's id. |
i18n |
The app's translator (a |
selected_language |
A reactive that returns the code of the language picked in the app
(for example |
introduction_ui() returns the page's UI as Shiny tags. introduction_server() is
called for its side effects.
## Not run: # the folder that holds 0_intro_en.md, 0_intro_fr.md and so on options(cd2030.help_dir = system.file("intro", package = "cd2030.rmncah")) # in the app's UI, and in its server function introduction_ui("introduction", i18n = i18n) introduction_server("introduction", selected_language = reactive(input$selected_language)) ## End(Not run)## Not run: # the folder that holds 0_intro_en.md, 0_intro_fr.md and so on options(cd2030.help_dir = system.file("intro", package = "cd2030.rmncah")) # in the app's UI, and in its server function introduction_ui("introduction", i18n = i18n) introduction_server("introduction", selected_language = reactive(input$selected_language)) ## End(Not run)
Default grouping of indicators used in CD2030 coverage framework
is_maternal_indicator(indicator)is_maternal_indicator(indicator)
indicator |
Character. Indicator name(s) to check, for example
|
TRUE if and indicator is maternal
is_maternal_indicator("anc4") is_maternal_indicator(c("anc4", "ideliv", "penta3"))is_maternal_indicator("anc4") is_maternal_indicator(c("anc4", "ideliv", "penta3"))
Returns all current groups (built-ins + any overrides).
list_indicator_groups()list_indicator_groups()
A sorted character vector of group names.
list_indicator_groups()list_indicator_groups()
Lists every district and month in which the value of one indicator is missing. Use it to see where the gaps behind a completeness summary are.
list_missing_units(.data, indicator, region = NULL)list_missing_units(.data, indicator, region = NULL)
.data |
A |
indicator |
Character. The indicator to check: one of the indicators of the dataset (for
example |
region |
Optional name of an |
A tibble of class cd_missing_list with one row per district and month where the
indicator is missing, and the columns adminlevel_1, district, year and month. The
attribute indicator holds the indicator.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) list_missing_units(data, "measles2") # Within one region list_missing_units(data, "measles2", region = "Rift Valley")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") data <- load_data(path) list_missing_units(data, "measles2") # Within one region list_missing_units(data, "measles2", region = "Rift Valley")
Flags extreme monthly values for every indicator at district level using the Hampel method.
list_outlier_units(.data)list_outlier_units(.data)
.data |
A |
Aggregates by year, month, and district.
Computes median and MAD (Median Absolute Deviation).
Flags outliers when values are more than 5 MAD from the median.
A cd_outlier_list tibble with:
Grouping columns
Raw values for each indicator
Median (<indicator>_med)
MAD (<indicator>_mad)
Outlier flag (<indicator>_outlier5std)
## Not run: list_outlier_units(cd_data) ## End(Not run)## Not run: list_outlier_units(cd_data) ## End(Not run)
Returns a subset of vaccines used in tracer metrics
list_tracer_vaccines()list_tracer_vaccines()
A character vector of tracer vaccines
list_tracer_vaccines() # those the selected indicator group has intersect(list_tracer_vaccines(), get_all_indicators())list_tracer_vaccines() # those the selected indicator group has intersect(list_tracer_vaccines(), get_all_indicators())
Returns a vector of standard vaccine and related indicators used in coverage and dropout analysis. This includes routine immunizations, tracer indicators, and derived dropout/coverage metrics commonly used in DHIS2-based health reporting.
list_vaccine_indicators()list_vaccine_indicators()
A character vector of vaccine indicator names
list_vaccine_indicators()list_vaccine_indicators()
Loads data via load_data() for Excel/Stata inputs, or initializes a cache
from an .rds. Returns a cache/connection object.
load_cache_data( path, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, on_conflict = c("replace", "merge", "error"), create_cache = FALSE, start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL, validate = TRUE )load_cache_data( path, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, on_conflict = c("replace", "merge", "error"), create_cache = FALSE, start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL, validate = TRUE )
path |
Path to |
indicator_group |
One of |
profile |
Optional. Either a name (string) of an existing group, or a definition to register inline before loading:
For |
on_conflict |
Conflict policy when |
create_cache |
Logical. For Excel/Stata inputs, whether to pass |
start_year |
Optional integer filter for minimum year. |
admin_sheet_name |
Excel sheet with admin data. Default |
population_sheet_name |
Excel sheet with population data. Default |
reporting_sheet_name |
Excel sheet with reporting completeness. Default |
service_sheet_names |
Character vector of service-data sheets.
Default: all sheets matching |
validate |
Logical. Whether to stop with an error when the merged data
fails a data quality check: |
A cache/connection object as returned by init_CacheConnection().
## Not run: # From Excel con <- load_cache_data("data/country.xlsx", indicator_group = "auto") # From Stata con <- load_cache_data("data/country.dta", indicator_group = "rmncah") # From pre-saved RDS con <- load_cache_data("data/cd_data.rds", indicator_group = "rmncah") ## End(Not run)## Not run: # From Excel con <- load_cache_data("data/country.xlsx", indicator_group = "auto") # From Stata con <- load_cache_data("data/country.dta", indicator_group = "rmncah") # From pre-saved RDS con <- load_cache_data("data/cd_data.rds", indicator_group = "rmncah") ## End(Not run)
Loads c-section correction estimates for national or area-level adjustment.
load_csection_estimates( path = NULL, .data = NULL, country_iso = NULL, level = c("national", "area") )load_csection_estimates( path = NULL, .data = NULL, country_iso = NULL, level = c("national", "area") )
path |
Optional. File path to a |
.data |
Optional. A pre-loaded dataset. Used directly if provided. |
country_iso |
ISO3 country code. When the data holds several countries (an |
level |
Either |
Filters data for the specified country_iso.
Validates whether the data level matches "national" or "area".
For "area" level, parses the level column to extract area.
Returns only relevant columns for merging (iso, year, indic, and either national or area_est).
A tibble of class "cd_csection_estimates" with a "level" attribute.
load_private_sector_data(), prepare_private_sector_plot_data()
## Not run: cs <- load_csection_estimates( path = "csection_national.dta", country_iso = "KEN", level = "national" ) ## End(Not run)## Not run: cs <- load_csection_estimates( path = "csection_national.dta", country_iso = "KEN", level = "national" ) ## End(Not run)
Loads a cleaned dataset from an Excel (.xlsx/.xls) or Stata (.dta) file,
optionally registers a profile override, and returns a tibble of class
cd_data. Group selection is resolved from the data inside new_countdown():
"auto" detects the best-matching group (built-ins + any overrides)
"vaccine" or "rmncah" select built-ins (overrides still apply)
"custom" uses profile (must exist after any inline registration)
load_data( path, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, on_conflict = c("replace", "merge", "error"), start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL, validate = TRUE )load_data( path, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, on_conflict = c("replace", "merge", "error"), start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL, validate = TRUE )
path |
Path to |
indicator_group |
One of |
profile |
Optional. Either a name (string) of an existing group, or a definition to register inline before loading:
For |
on_conflict |
Conflict policy when |
start_year |
Optional integer filter for minimum year. |
admin_sheet_name |
Excel sheet with admin data. Default |
population_sheet_name |
Excel sheet with population data. Default |
reporting_sheet_name |
Excel sheet with reporting completeness. Default |
service_sheet_names |
Character vector of service-data sheets.
Default: all sheets matching |
validate |
Logical. Whether to stop with an error when the merged data
fails a data quality check: |
The actual group resolution occurs in new_countdown(), using indicators
from the loaded data. If profile is a definition, it is registered via
register_indicator_group() before loading, so auto-detection considers it.
A tibble of class cd_data.
## Not run: # Built-in group (explicit) cd <- load_data("data/country.dta", indicator_group = "rmncah") attr(cd, "indicator_group") # "rmncah" # Auto-detect among built-ins cd <- load_data("data/country.xlsx", indicator_group = "auto") # Inline extend rmncah, then auto-detect (merge by category) cd <- load_data( "data/country.xlsx", indicator_group = "auto", profile = list(name = "rmncah", value = list(hiv = c("hiv_test","pmtct1"))), on_conflict = "merge" ) # Define a brand-new custom profile and select it cd <- load_data( "data/country.xlsx", indicator_group = "custom", profile = list(my_profile = list(anc = c("anc1","anc4"))) ) ## End(Not run)## Not run: # Built-in group (explicit) cd <- load_data("data/country.dta", indicator_group = "rmncah") attr(cd, "indicator_group") # "rmncah" # Auto-detect among built-ins cd <- load_data("data/country.xlsx", indicator_group = "auto") # Inline extend rmncah, then auto-detect (merge by category) cd <- load_data( "data/country.xlsx", indicator_group = "auto", profile = list(name = "rmncah", value = list(hiv = c("hiv_test","pmtct1"))), on_conflict = "merge" ) # Define a brand-new custom profile and select it cd <- load_data( "data/country.xlsx", indicator_group = "custom", profile = list(my_profile = list(anc = c("anc1","anc4"))) ) ## End(Not run)
Loads survey equity data, removes unnecessary variables, and filters by country.
load_equity_data(path = NULL, .data = NULL, country_iso)load_equity_data(path = NULL, .data = NULL, country_iso)
path |
Optional. File path to a |
.data |
Optional. A preloaded data frame. |
country_iso |
Character. ISO3 country code to filter by. |
A tibble of class cd_equity_data.
## Not run: wealth <- load_equity_data(path = "wiq_data.dta", country_iso = "KEN") cache$set_wiq_survey(wealth) # The same for the survey by area of residence and by mother's education cache$set_area_survey(load_equity_data(path = "area_data.dta", country_iso = "KEN")) cache$set_education_survey(load_equity_data(path = "meduc_data.dta", country_iso = "KEN")) ## End(Not run)## Not run: wealth <- load_equity_data(path = "wiq_data.dta", country_iso = "KEN") cache$set_wiq_survey(wealth) # The same for the survey by area of residence and by mother's education cache$set_area_survey(load_equity_data(path = "area_data.dta", country_iso = "KEN")) cache$set_education_survey(load_equity_data(path = "meduc_data.dta", country_iso = "KEN")) ## End(Not run)
Reads and cleans each sheet of a Countdown 2030 Excel workbook and returns the sheets
separately, without merging them. Use it to run data quality checks on each sheet before
the merge, then pass the result to merge_and_standardize() to finish loading.
load_excel_parts( path, start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL )load_excel_parts( path, start_year = NULL, admin_sheet_name = NULL, population_sheet_name = NULL, reporting_sheet_name = NULL, service_sheet_names = NULL )
path |
Path to an |
start_year |
Optional integer filter for minimum year. |
admin_sheet_name |
Excel sheet with admin data. Default |
population_sheet_name |
Excel sheet with population data. Default |
reporting_sheet_name |
Excel sheet with reporting completeness. Default |
service_sheet_names |
Character vector of service-data sheets.
Default: all sheets matching |
Month names are standardized to English on every sheet that has a month column, and the
original text is kept in a raw_month column. The sheets can then be joined on month even
if they name the months in different languages.
The function stops with an error if a named sheet is not in the workbook, if a sheet is
empty, or if a sheet lacks its key columns (district for the Admin sheet, district and
year for the Population sheet, and district, year and month for the others). Other
problems with the data are left to the data quality checks.
A list with these elements:
parts: a named list of cleaned tibbles, one per sheet, named by sheet.
sheet_names: a character vector of the sheet names, in the order the sheets are merged.
sheet_ids: a named list of the key columns of the Admin sheet, the Population sheet
and (as service_data) every other sheet.
admin_sheet_name, population_sheet_name, reporting_sheet_name,
service_sheet_names: the sheet names used, with defaults filled in.
path, start_year: the arguments as given.
merge_and_standardize(), run_all_quality_checks()
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) names(sheets$parts) sheets$service_sheet_names sheets$parts[[sheets$population_sheet_name]] # Month names are in English, the workbook's own text is kept beside them unique(sheets$parts[[sheets$service_sheet_names[1]]][c("month", "raw_month")])path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) names(sheets$parts) sheets$service_sheet_names sheets$parts[[sheets$population_sheet_name]] # Month names are in English, the workbook's own text is kept beside them unique(sheets$parts[[sheets$service_sheet_names[1]]][c("month", "raw_month")])
load_fpet_data loads Family Planning Estimation Tool (FPET) data from a .csv
file, or uses a pre-supplied dataset. It assigns a country ISO code if specified,
and returns a tibble with a custom class cd_fpet_data.
load_fpet_data(path = NULL, .data = NULL, country_iso = NULL)load_fpet_data(path = NULL, .data = NULL, country_iso = NULL)
path |
Optional |
.data |
Optional |
country_iso |
Optional |
A tibble with class cd_fpet_data. If country_iso is provided, the
data is filtered by iso3 == country_iso.
## Not run: # Load FPET data from file fpet <- load_fpet_data(path = "path/to/fpet.csv", country_iso = "NGA") # Use existing data fpet <- load_fpet_data(.data = some_fpet_data, country_iso = "ETH") ## End(Not run)## Not run: # Load FPET data from file fpet <- load_fpet_data(path = "path/to/fpet.csv", country_iso = "NGA") # Use existing data fpet <- load_fpet_data(.data = some_fpet_data, country_iso = "ETH") ## End(Not run)
Loads raw prevalence data for public/private sector analysis and applies internal preprocessing for c-section share calculation.
load_private_sector_data( path = NULL, .data = NULL, country_iso = NULL, level = c("national", "area") )load_private_sector_data( path = NULL, .data = NULL, country_iso = NULL, level = c("national", "area") )
path |
Optional. File path to a |
.data |
Optional. A pre-loaded dataset. Used directly if provided. |
country_iso |
ISO3 country code. When the data holds several countries (an |
level |
Either |
Loads the data from path, or uses .data, and checks that it matches level: area data has a
level column and national data does not. Then:
Assigns "Public" or "Private" to the sector column based on indic suffix.
Removes sector suffix from indic.
Computes number of c-sections (num_csection) and sector share of c-sections (share_csection)
within each country and survey year, and within each value of the level column for area data.
If level is "area", parses level string into area = "Urban" or "Rural".
A tibble of class "cd_private_sector_data" with a "level" attribute.
indic: cleaned indicator name (without "pub"/"priv")
sector: "Public" or "Private"
share_csection: share of c-sections attributable to each sector
area: (only if level == "area")
load_csection_estimates(), prepare_private_sector_plot_data()
## Not run: dt <- load_private_sector_data( path = "National estimates.dta", country_iso = "KEN", level = "national" ) ## End(Not run)## Not run: dt <- load_private_sector_data( path = "National estimates.dta", country_iso = "KEN", level = "national" ) ## End(Not run)
Loads national or subnational survey data, cleans labels and codes, and applies country-specific adjustments for admin-level naming.
load_survey_data( path = NULL, .data = NULL, country_iso, admin_level = c("national", "adminlevel_1") )load_survey_data( path = NULL, .data = NULL, country_iso, admin_level = c("national", "adminlevel_1") )
path |
Optional. File path to a |
.data |
Optional. A preloaded data frame. |
country_iso |
Character. Country ISO3 code. |
admin_level |
Character. One of |
A tibble of class cd_survey_data.
## Not run: national <- load_survey_data(path = "all_data.dta", country_iso = "KEN") cache$set_national_survey(national) # The survey by region regional <- load_survey_data( path = "gregion_data.dta", country_iso = "KEN", admin_level = "adminlevel_1" ) cache$set_regional_survey(regional) ## End(Not run)## Not run: national <- load_survey_data(path = "all_data.dta", country_iso = "KEN") cache$set_national_survey(national) # The survey by region regional <- load_survey_data( path = "gregion_data.dta", country_iso = "KEN", admin_level = "adminlevel_1" ) cache$set_regional_survey(regional) ## End(Not run)
Loads and processes UN estimates from a .dta file or in-memory data.
Filters by country and year, renames columns, and assigns a custom class.
load_un_estimates(path = NULL, .data = NULL, country_iso, start_year, end_year)load_un_estimates(path = NULL, .data = NULL, country_iso, start_year, end_year)
path |
Optional. File path to a |
.data |
Optional. A preloaded data frame. |
country_iso |
Character. ISO3 code of the country. |
start_year, end_year
|
Integers. First and last year (inclusive) to include. |
A tibble of class cd_un_estimates.
## Not run: un <- load_un_estimates( path = "un_estimates.dta", country_iso = "KEN", start_year = 2019, end_year = 2023 ) # From data already read, then kept with the dataset un <- load_un_estimates(.data = all_un, country_iso = "KEN", start_year = 2019, end_year = 2023) cache$set_un_estimates(un) ## End(Not run)## Not run: un <- load_un_estimates( path = "un_estimates.dta", country_iso = "KEN", start_year = 2019, end_year = 2023 ) # From data already read, then kept with the dataset un <- load_un_estimates(.data = all_un, country_iso = "KEN", start_year = 2019, end_year = 2023) cache$set_un_estimates(un) ## End(Not run)
Loads UN mortality data from a file path or existing data frame, filters it by the given country ISO3 code, and returns cleaned mortality data sorted by year.
load_un_mortality_data(path = NULL, .data = NULL, country_iso)load_un_mortality_data(path = NULL, .data = NULL, country_iso)
path |
Optional. Path to an Excel or CSV file containing UN mortality estimates. |
.data |
Optional. A pre-loaded data frame with UN mortality estimates. |
country_iso |
Required. A 3-letter ISO country code used to filter the dataset. |
A tibble of class cd_un_mortality.
## Not run: load_un_mortality_data("data/un_mortality.csv", country_iso = "KEN") load_un_mortality_data(.data = df, country_iso = "UGA") ## End(Not run)## Not run: load_un_mortality_data("data/un_mortality.csv", country_iso = "KEN") load_un_mortality_data(.data = df, country_iso = "UGA") ## End(Not run)
Loads and processes WUENIC estimates, computes dropout and zero-dose indicators, and standardizes naming conventions.
load_wuenic_data(path = NULL, .data = NULL, country_iso)load_wuenic_data(path = NULL, .data = NULL, country_iso)
path |
Optional. File path to a |
.data |
Optional. A preloaded data frame. |
country_iso |
Character. ISO3 country code. |
A tibble of class cd_wuenic_data.
## Not run: wuenic <- load_wuenic_data(path = "wuenic.dta", country_iso = "KEN") wuenic[c("year", "cov_penta3_wuenic", "cov_dropout_penta13_wuenic")] cache$set_wuenic_estimates(wuenic) ## End(Not run)## Not run: wuenic <- load_wuenic_data(path = "wuenic.dta", country_iso = "KEN") wuenic[c("year", "cov_penta3_wuenic", "cov_dropout_penta13_wuenic")] cache$set_wuenic_estimates(wuenic) ## End(Not run)
The user matches each admin level 1 name of the dataset to the name the shapefile uses for
the same area. A button opens the matching dialog (mapping_modal_ui()); saving it stores the
mapping with cache()$set_map_mapping(). The names come from the shapefile in use (the one
the user uploaded, or the built-in one for the country), in the column
cache()$shapefile_name_field. Once a mapping is saved, a "clear mapping" button removes it
(cache()$clear_map_mapping()) and a banner says how the names were matched
(mapping_provenance_banner()). The step counts as complete when a mapping is saved (see
step_map_mapping_complete()), which needs the user to save the dialog at least once.
map_shapefile_ui(id, i18n) map_shapefile_server(id, cache, i18n)map_shapefile_ui(id, i18n) map_shapefile_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
map_shapefile_ui() returns the UI as Shiny tags: a card. map_shapefile_server() is
called for its side effects and returns nothing useful.
## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "map_mapping", ui = map_shapefile_ui(ns("map_shapefile"), i18n)) map_shapefile_server("map_shapefile", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "map_mapping", ui = map_shapefile_ui(ns("map_shapefile"), i18n)) map_shapefile_server("map_shapefile", cache, i18n) ## End(Not run)
The user matches each admin level 1 name of the dataset to the name the regional survey uses
for the same area. A button opens the matching dialog (mapping_modal_ui()); saving it stores
the mapping with cache()$set_survey_mapping(). The regional survey is the one the user
uploaded, or the built-in one for the country, so the step can always be done. Once a mapping
is saved, a "clear mapping" button removes it (cache()$clear_survey_mapping()) and a banner
says how the names were matched (mapping_provenance_banner()). The step counts as complete
when a mapping is saved (see step_survey_mapping_complete()), which needs the user to save
the dialog at least once.
map_survey_ui(id, i18n) map_survey_server(id, cache, i18n)map_survey_ui(id, i18n) map_survey_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
map_survey_ui() returns the UI as Shiny tags: a card. map_survey_server() is called
for its side effects and returns nothing useful.
## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "survey_mapping", ui = map_survey_ui(ns("map_survey"), i18n)) map_survey_server("map_survey", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "survey_mapping", ui = map_survey_ui(ns("map_survey"), i18n)) map_survey_server("map_survey", cache, i18n) ## End(Not run)
A button that opens a dialog with one row per admin level 1 name of the dataset
(cache()$subnational_regions). In each row the user picks the matching name from another
source: the regional survey or the shapefile. The dialog suggests matches itself and keeps
the matches saved before. When the user saves, the server stores the mapping in the dataset
with cache()$set_survey_mapping() or cache()$set_map_mapping(), depending on type. The
two mapping steps of the wizard use it (map_survey_ui(), map_shapefile_ui()).
mapping_modal_ui(id) mapping_modal_server( id, cache, survey_data, survey_map, label, title, show_col, type, i18n )mapping_modal_ui(id) mapping_modal_server( id, cache, survey_data, survey_map, label, title, show_col, type, i18n )
id |
The module's id. |
cache |
A reactive that returns the dataset, a CacheConnection. |
survey_data |
A reactive that returns the other source, a data frame (the regional
survey, or the shapefile). Its |
survey_map |
A reactive that returns the mapping saved so far (a data frame as described
in Details), or |
label |
The translation key of the button's text, a string. |
title |
The translation key of the dialog's title, a string. |
show_col |
The column of |
type |
Where the mapping is saved: |
i18n |
The app's translator (a |
The saved mapping is a tibble with one row per matched name and three columns:
admin_level_1 (the dataset's name), a column named after show_col (the matching name in
the other source) and source ("auto" when the row is the dialog's own suggestion, left
unchanged, and "user" otherwise). Rows the user left without a match are not saved.
The button and dialog appear once the dataset has its admin level 1 names and survey_data()
has a value.
mapping_modal_ui() returns the UI as Shiny tags: the placeholder the server fills
with the button and its dialog. mapping_modal_server() is called for its side effects and
returns nothing useful.
## Not run: # in a module's ui mapping_modal_ui(ns("survey_data")) # in its server: match the dataset's names to the regional survey's mapping_modal_server( id = "survey_data", cache = cache, survey_data = reactive(cache()$regional_survey), survey_map = reactive(cache()$survey_mapping), label = "btn_upload_map_survey", title = "msg_upload_manual_mapping", show_col = "adminlevel_1", type = "survey_mapping", i18n = i18n ) ## End(Not run)## Not run: # in a module's ui mapping_modal_ui(ns("survey_data")) # in its server: match the dataset's names to the regional survey's mapping_modal_server( id = "survey_data", cache = cache, survey_data = reactive(cache()$regional_survey), survey_map = reactive(cache()$survey_mapping), label = "btn_upload_map_survey", title = "msg_upload_manual_mapping", show_col = "adminlevel_1", type = "survey_mapping", i18n = i18n ) ## End(Not run)
Builds the information banner the two mapping steps show under their status message once a
mapping is saved. It says how many of the saved matches were made automatically and how many
the user chose, from the mapping's source column ("auto" or "user" per row, written by
mapping_modal_server()).
mapping_provenance_banner(mapping_df, i18n)mapping_provenance_banner(mapping_df, i18n)
mapping_df |
The saved mapping, a data frame with a |
i18n |
The app's translator (a |
The banner as Shiny tags, or NULL when mapping_df is NULL, has no rows or has no
source column.
## Not run: # in a module's server: under the mapping's button, say how the saved names were matched output$survey_map_summary <- renderUI(mapping_provenance_banner(cache()$survey_mapping, i18n)) # the banner for a mapping of three names, two matched by the dialog and one by the user mapping <- data.frame( admin_level_1 = c("Nairobi", "Mombasa", "Kisumu"), adminlevel_1 = c("Nairobi", "Mombasa", "Kisumu"), source = c("auto", "auto", "user") ) mapping_provenance_banner(mapping, i18n) ## End(Not run)## Not run: # in a module's server: under the mapping's button, say how the saved names were matched output$survey_map_summary <- renderUI(mapping_provenance_banner(cache()$survey_mapping, i18n)) # the banner for a mapping of three names, two matched by the dialog and one by the user mapping <- data.frame( admin_level_1 = c("Nairobi", "Mombasa", "Kisumu"), adminlevel_1 = c("Nairobi", "Mombasa", "Kisumu"), source = c("auto", "auto", "user") ) mapping_provenance_banner(mapping, i18n) ## End(Not run)
load_excel_parts()
Merges the separate sheets returned by load_excel_parts() into one dataset, standardizes
its columns and returns it as a cd_data tibble. This is the second half of loading an
Excel workbook.
merge_and_standardize( parts_result, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, profile_name = NULL, validate = TRUE )merge_and_standardize( parts_result, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile = NULL, profile_name = NULL, validate = TRUE )
parts_result |
A list. What |
indicator_group |
One of |
profile |
Optional. Either a name (string) of an existing group, or a definition to register inline before loading:
For |
profile_name |
Optional. The resolved profile (indicator group) name,
used when resolving the indicator group (for example with
|
validate |
Logical. Whether to stop with an error when the merged data
fails a data quality check: |
Before merging, the function stops with an error if the Admin sheet fails
check_admin_columns() or check_single_country(). The merged data then goes to
new_countdown(), which resolves the indicator group and, when validate is TRUE, stops
on a data quality problem.
A tibble of class cd_data.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) data <- merge_and_standardize(sheets) data # Load even if a data quality check fails, to run the checks afterwards data <- merge_and_standardize(sheets, validate = FALSE)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) data <- merge_and_standardize(sheets) data # Load even if a data quality check fails, to run the checks afterwards data <- merge_and_standardize(sheets, validate = FALSE)
Shows national coverage by year for each indicator: the estimate from the health facility data,
with the denominator selected for the indicator, beside the survey and WUENIC estimates. The page
is the coverage charts (coverage_ui()) at the national level: one card with a tab for each
indicator in cd_cfg("nat_cov_indicators") and a Custom tab. It has no filters. The data come
from the dataset's get_filtered_coverage(), which reads
cache()$calculate_coverage("national").
national_coverage_ui(id, i18n) national_coverage_server(id, cache, i18n, active = reactive(TRUE))national_coverage_ui(id, i18n) national_coverage_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
national_coverage_ui() returns the page's UI as Shiny tags.
national_coverage_server() returns what coverage_server() returns: a reactive that holds
the key of the tab shown.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_coverage", ui = national_coverage_ui, server = national_coverage_server, title = "title_coverage_national", section = "title_nav_national_analysis", subtitle = "sub_cov_national" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_coverage", ui = national_coverage_ui, server = national_coverage_server, title = "title_coverage_national", section = "title_nav_national_analysis", subtitle = "sub_cov_national" ) ## End(Not run)
Shows how coverage differs between the admin level 1 areas of the country, in two cards. The
first is the inequality charts (inequality_ui()): each area's coverage by year against national
coverage, from cache()$inequality_admin1. The second is the maps of the same coverage
(subnational_mapping_ui()), from the dataset's get_filtered_mapping_data(); changing the tab
of the charts changes the tab of the maps too. Two controls above the maps apply to the maps
only: the years to map, which are saved in the dataset (set_mapping_years()), and the colour
palette.
national_inequality_ui(id, i18n) national_inequality_server(id, cache, i18n, active = reactive(TRUE))national_inequality_ui(id, i18n) national_inequality_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
national_inequality_ui() returns the page's UI as Shiny tags.
national_inequality_server() is called for its side effects; its value (the observer that
saves the chosen years) is of no use to a caller.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_inequality", ui = national_inequality_ui, server = national_inequality_server, title = "title_inequ_national", section = "title_nav_national_analysis", subtitle = "sub_inequ_national" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_inequality", ui = national_inequality_ui, server = national_inequality_server, title = "title_inequ_national", section = "title_nav_national_analysis", subtitle = "sub_inequ_national" ) ## End(Not run)
Return the names of the values that must be set before the National Rates step counts as
complete: every field of the app's wizard configuration (cd_wizard_config()).
national_rates_required_fields() gives the national rates, which are elements of the
dataset's national_estimates. survey_estimates_required_fields() gives the survey coverage
estimates, which are elements of the dataset's survey_estimates. They are functions because
the list differs between apps and is read from the configuration when called.
national_rates_required_fields() survey_estimates_required_fields()national_rates_required_fields() survey_estimates_required_fields()
A character vector of names, in display order: the key of every "rate" field for
national_rates_required_fields(), and of every "survey" field for
survey_estimates_required_fields().
step_national_rates_complete(), which uses both.
old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_survey_field("ideliv_prop", "instlivebirths", "title_upload_ideliv_survey"), cd_wizard_national_rate_fields() ) ))) national_rates_required_fields() survey_estimates_required_fields() options(old)old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_survey_field("ideliv_prop", "instlivebirths", "title_upload_ideliv_survey"), cd_wizard_national_rate_fields() ) ))) national_rates_required_fields() survey_estimates_required_fields() options(old)
The user enters the national figures the denominators are calculated from: the survey
coverage estimates (in percent) and national rates (as proportions) listed in the app's
wizard configuration (cd_wizard_config()), the year of the most recent survey, and the year
the surveys start from. The fields show what the dataset already holds, so values taken from
an uploaded national survey appear filled in; a banner says so when the user has uploaded a
national survey. Each change is saved to the dataset shortly after it is made. The step
counts as complete when every listed field has a value and the survey year is set (see
step_national_rates_complete()).
national_rates_ui(id, i18n) national_rates_server(id, cache, i18n)national_rates_ui(id, i18n) national_rates_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
What is saved:
survey coverage estimates, rounded to one decimal place, with
cache()$set_survey_estimates();
national rates, rounded to three decimal places, with cache()$set_national_estimates();
the most recent survey year (2015 to 2030) with cache()$set_survey_year(), or
cache()$clear_survey_year() when the user empties the field;
the survey start year with cache()$set_start_survey_year(). This field is a list of
cache()$survey_years and only shows when the dataset has survey years. When the saved
start year is not one of them, the earliest is saved in its place.
Emptying an estimate or a rate field saves a missing value (NA) for it, which makes the
step incomplete again.
national_rates_ui() returns the UI as Shiny tags: a card with the groups of fields.
national_rates_server() is called for its side effects and returns nothing useful.
## Not run: # the app describes the step's fields once, before the wizard is used options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "national_rates", ui = national_rates_ui(ns("national_rates"), i18n)) national_rates_server("national_rates", cache, i18n) ## End(Not run)## Not run: # the app describes the step's fields once, before the wizard is used options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "national_rates", ui = national_rates_ui(ns("national_rates"), i18n)) national_rates_server("national_rates", cache, i18n) ## End(Not run)
Shows how much of the country meets the coverage targets. One filter chooses the admin level
(admin level 1 or district). The page is the target charts and table (target_ui()) for the
whole country: by year, the percentage of regions or districts that meet each target group's
target (the dataset's get_filtered_threshold()), and a table of the areas whose coverage of a
chosen indicator reaches the target (the dataset's get_high_performers()).
national_target_ui(id, i18n) national_target_server(id, cache, i18n, active = reactive(TRUE))national_target_ui(id, i18n) national_target_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
national_target_ui() returns the page's UI as Shiny tags. national_target_server()
returns what target_server() returns: a reactive that holds the key of the tab shown.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_target", ui = national_target_ui, server = national_target_server, title = "title_nav_global_coverage", section = "title_nav_national_analysis", subtitle = "sub_target_national" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "national_target", ui = national_target_ui, server = national_target_server, title = "title_nav_global_coverage", section = "title_nav_national_analysis", subtitle = "sub_target_national" ) ## End(Not run)
cd_data object from cleaned data and resolve the indicator groupValidates required columns, resolves the concrete indicator group name from
the data ("auto" detection supported), ensures the selected group's
indicators are fully present, sets the global selection, and returns a cd_data.
new_countdown( .data, class = NULL, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile_name = NULL, profile = NULL, validate = TRUE )new_countdown( .data, class = NULL, indicator_group = c("auto", "vaccine", "rmncah", "custom"), profile_name = NULL, profile = NULL, validate = TRUE )
.data |
Tibble after cleaning/merge. |
class |
Optional character vector of extra classes to add in front of
|
indicator_group |
One of |
profile_name |
Optional. The resolved profile (indicator group) name,
used when resolving the indicator group (for example with
|
profile |
For |
validate |
Logical. Whether to run the Tier B quality checks (district
consistency, month presence and month validity). Default is |
A tibble with class cd_data and attr(, "indicator_group") set to
the resolved name. Also sets options(cd2030.selected_group) via set_selected_group().
## Not run: x <- .load_excel_data("data/country.xlsx", indicator_group = "auto") cd <- new_countdown(x, indicator_group = "auto") attr(cd, "indicator_group") ## End(Not run)## Not run: x <- .load_excel_data("data/country.xlsx", indicator_group = "auto") cd <- new_countdown(x, indicator_group = "auto") attr(cd, "indicator_group") ## End(Not run)
Lists, prepares, attaches or describes the datasets of a folder for notebooks in R, Python and
Stata. A dataset is the .rds file an app saved next to a country's Excel file, together with
its workspace. DataSuite calls this function for the apps that declare it as their
notebookData. It does not write to an .xlsx or .rds file: it writes only to the
workspace's data/ folder.
notebook_data( action = c("list", "prepare", "attach", "describe"), folder, workspace = NULL, datasets = NULL, force = FALSE, period = 60, tables = NULL )notebook_data( action = c("list", "prepare", "attach", "describe"), folder, workspace = NULL, datasets = NULL, force = FALSE, period = 60, tables = NULL )
action |
|
folder |
The folder holding the Excel files, the |
workspace |
The notebook's workspace folder ( |
datasets |
For |
force |
For |
period |
Seconds between checks of an |
tables |
For |
For "list", "prepare" and "describe", a list (DataSuite reads it as JSON); for "attach",
invisibly the names attached.
# a folder with a country's Excel file that no app has opened yet folder <- tempfile("countdown_") dir.create(folder) file.copy(system.file("extdata", "kenya.xlsx", package = "cd2030.core"), folder) listing <- notebook_data("list", folder = folder) listing$datasets[[1]]$status vapply(listing$ref$tables, function(t) t$name, character(1)) unlink(folder, recursive = TRUE) ## Not run: # in a notebook of the workspace of kenya_rmncah.rds: its tables by name, and ds_list() workspace <- file.path("data", "kenya_rmncah.shiny-workspace") notebook_data("attach", folder = "data", workspace = workspace) head(adjusted_data) # for Python and Stata: Stata files of two of its tables in the workspace's data/ folder notebook_data("prepare", folder = "data", workspace = workspace, tables = c("adjusted_data", "national_survey")) ## End(Not run)# a folder with a country's Excel file that no app has opened yet folder <- tempfile("countdown_") dir.create(folder) file.copy(system.file("extdata", "kenya.xlsx", package = "cd2030.core"), folder) listing <- notebook_data("list", folder = folder) listing$datasets[[1]]$status vapply(listing$ref$tables, function(t) t$name, character(1)) unlink(folder, recursive = TRUE) ## Not run: # in a notebook of the workspace of kenya_rmncah.rds: its tables by name, and ds_list() workspace <- file.path("data", "kenya_rmncah.shiny-workspace") notebook_data("attach", folder = "data", workspace = workspace) head(adjusted_data) # for Python and Stata: Stata files of two of its tables in the workspace's data/ folder notebook_data("prepare", folder = "data", workspace = workspace, tables = c("adjusted_data", "national_survey")) ## End(Not run)
Builds one labelled number field with the interface kit's cd_field_number(). The field
checks what is typed against min and max, shows an error under the field for a value out
of range, and sends only a valid value to the server. A required field that is empty shows a
"not set" warning. A field whose hint is "hint_upload_percent" shows a "%" unit at its end.
nr_field(ns, i18n, inputId, labelKey, min, max, step, hintKey, required = TRUE)nr_field(ns, i18n, inputId, labelKey, min, max, step, hintKey, required = TRUE)
ns |
The namespace function of the module the field belongs to (from |
i18n |
The app's translator (a |
inputId |
The input id of the field, without the namespace, a string. |
labelKey |
The translation key of the field's label, a string. |
min, max
|
The smallest and largest value the field accepts, numbers. |
step |
The amount one step of the field changes the value by, a number. |
hintKey |
The translation key of the hint under the field, a string, or |
required |
|
The field as Shiny tags.
## Not run: # in a module's ui, where ns <- NS(id) nr_field(ns, i18n, "anc4_prop", "title_upload_anc4_survey", 0, 100, 1, "hint_upload_percent") # a field without a hint, which may be left empty nr_field(ns, i18n, "survey_year", "title_upload_recent_survey_year", 2015, 2030, 1, NULL, required = FALSE ) # from a field description of the app's wizard configuration f <- cd_wizard_rate_field("stillbirth_rate", "sbr", "title_upload_stillbirth") nr_field(ns, i18n, f$id, f$label_key, f$min, f$max, f$step, f$hint) ## End(Not run)## Not run: # in a module's ui, where ns <- NS(id) nr_field(ns, i18n, "anc4_prop", "title_upload_anc4_survey", 0, 100, 1, "hint_upload_percent") # a field without a hint, which may be left empty nr_field(ns, i18n, "survey_year", "title_upload_recent_survey_year", 2015, 2030, 1, NULL, required = FALSE ) # from a field description of the app's wizard configuration f <- cd_wizard_rate_field("stillbirth_rate", "sbr", "title_upload_stillbirth") nr_field(ns, i18n, f$id, f$label_key, f$min, f$max, f$step, f$hint) ## End(Not run)
Lays out fields in a grid under a title and a subtitle. The National Rates step uses it for each group of fields, and the Upload Data step for its reference-data upload zones.
nr_group(i18n, titleKey, subtitleKey, ..., cols = 4)nr_group(i18n, titleKey, subtitleKey, ..., cols = 4)
i18n |
The app's translator (a |
titleKey |
The translation key of the group's title, a string. |
subtitleKey |
The translation key of the group's subtitle, a string. |
... |
The fields of the group, as Shiny tags (for example from |
cols |
The number of columns of the grid, a whole number. The default is 4. |
The group as Shiny tags.
## Not run: # in a module's ui, where ns <- NS(id) nr_group(i18n, "title_upload_group_survey_ref", "sub_upload_group_survey_ref", nr_field(ns, i18n, "survey_year", "title_upload_recent_survey_year", 2015, 2030, 1, NULL), uiOutput(ns("survey_start_ui")) ) # two columns in place of four nr_group(i18n, "title_upload_group_immunization", "sub_upload_group_immunization", nr_field(ns, i18n, "penta3_prop", "title_upload_penta3_survey", 0, 100, 1, "hint_upload_percent"), nr_field(ns, i18n, "bcg_prop", "title_upload_bcg_survey", 0, 100, 1, "hint_upload_percent"), cols = 2 ) ## End(Not run)## Not run: # in a module's ui, where ns <- NS(id) nr_group(i18n, "title_upload_group_survey_ref", "sub_upload_group_survey_ref", nr_field(ns, i18n, "survey_year", "title_upload_recent_survey_year", 2015, 2030, 1, NULL), uiOutput(ns("survey_start_ui")) ) # two columns in place of four nr_group(i18n, "title_upload_group_immunization", "sub_upload_group_immunization", nr_field(ns, i18n, "penta3_prop", "title_upload_penta3_survey", 0, 100, 1, "hint_upload_percent"), nr_field(ns, i18n, "bcg_prop", "title_upload_bcg_survey", 0, 100, 1, "hint_upload_percent"), cols = 2 ) ## End(Not run)
The data quality page on extreme values in the monthly data. Its first card has three tabs for the chosen indicator: a heat map of the outlier summary by admin level 1 area or district, a bar chart by indicator and a bar chart by area. Below it are a table of the districts and months flagged as outliers in the year picked on the table (the reported value with its median and median absolute deviation), and a trend chart of those outliers for one region and that year. The filters are the indicator and the admin level with its region. The trend chart has its own region filter, which follows the page's region.
outlier_detection_ui(id, i18n) outlier_detection_server(id, cache, i18n, active = reactive(TRUE))outlier_detection_ui(id, i18n) outlier_detection_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
The page reads outliers_admin1, outliers_district and list_outlier_units from the dataset,
and calls its calculate_outliers_summary() when a region is chosen. The heat map's Excel
download also writes outliers_national and district_outliers_summary.
outlier_detection_ui() returns the page's UI as Shiny tags.
outlier_detection_server() is called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "outlier_detection", ui = outlier_detection_ui, server = outlier_detection_server, title = "title_outlier_main", section = "lbl_nav_section_quality", subtitle = "sub_outlier_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "outlier_detection", ui = outlier_detection_ui, server = outlier_detection_server, title = "title_outlier_main", section = "lbl_nav_section_quality", subtitle = "sub_outlier_main" ) ## End(Not run)
The data quality page that brings the checks together in one table: the completeness of monthly reporting, extreme outliers and the consistency of annual reporting, with a score for each year of the data. The one filter is the region: with none chosen the table is for the country, otherwise it is for that admin level 1 area. The table can be downloaded.
overall_score_ui(id, i18n) overall_score_server(id, cache, i18n, active = reactive(TRUE))overall_score_ui(id, i18n) overall_score_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
The page calls the dataset's calculate_overall_score(), and reads its performance_threshold
(shown in a row label) and data_years.
overall_score_ui() returns the page's UI as Shiny tags. overall_score_server() is
called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "overall_score", ui = overall_score_ui, server = overall_score_server, title = "title_score_main", section = "lbl_nav_section_quality", subtitle = "sub_score_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "overall_score", ui = overall_score_ui, server = overall_score_server, title = "title_score_main", section = "lbl_nav_section_quality", subtitle = "sub_score_main" ) ## End(Not run)
These functions generate scatter plots that compare two health indicators across years, assessing internal consistency through visualization of linear regression fits and R-squared values by year. Each function is designed to compare a specific pair of indicators, with options for customizing plot titles, axis labels, and the inclusion of trend information.
plot_comparison_anc1_penta1() compares ANC1 and Penta1. Its title is "Comparison of numbers of ANC1 and Penta1 by year" and its axes are titled "ANC1" and "Penta1" unless others are given; the two functions below are the same for their pairs.
plot_comparison_penta1_penta3() compares Penta1 and Penta3.
plot_comparison_opv1_opv3() compares OPV1 and OPV3.
plot_comparison( .data, x_var, y_var, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, call = caller_env() ) plot_comparison_anc1_penta1( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL ) plot_comparison_penta1_penta3( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL ) plot_comparison_opv1_opv3( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )plot_comparison( .data, x_var, y_var, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, call = caller_env() ) plot_comparison_anc1_penta1( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL ) plot_comparison_penta1_penta3( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL ) plot_comparison_opv1_opv3( .data, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
.data |
A data frame of class |
x_var |
Character. The name of the indicator variable to plot on the x-axis. |
y_var |
Character. The name of the indicator variable to plot on the y-axis. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional named list or vector overriding the legend labels.
Recognised names are |
call |
The calling environment, used for error handling. Default is |
options |
A |
The scatter plot displays the relationship between the two specified indicators over multiple years, with each year presented in a separate facet.
A linear regression line is added to each year's plot to help visualize the trend.
R-squared values, calculated per year, are optionally displayed on each facet, indicating the strength of the linear relationship between the indicators for that year.
A diagonal reference line is also provided for visual comparison to a 1:1 relationship, where applicable.
This function is commonly used for consistency checks between indicators such as:
ANC1 vs PENTA1
PENTA1 vs PENTA3
OPV1 vs OPV3
A ggplot2 object, comprising:
A scatter plot comparing two specified indicators over multiple years.
A linear regression line for each year, indicating the trend between the indicators.
Optional display of R-squared values per facet, summarizing the correlation strength.
Faceting by year to facilitate a detailed comparison of trends across years.
Users can render this ggplot2 object directly, save it, or further modify it using the + operator.
## Not run: # Plot a comparison between ANC1 and PENTA1 indicators plot_comparison(cd_data, x_var = "anc1", y_var = "penta1") # Dedicated function for comparing ANC1 and PENTA1 over time plot_comparison_penta1_anc1(cd_data) ## End(Not run)## Not run: # Plot a comparison between ANC1 and PENTA1 indicators plot_comparison(cd_data, x_var = "anc1", y_var = "penta1") # Dedicated function for comparing ANC1 and PENTA1 over time plot_comparison_penta1_anc1(cd_data) ## End(Not run)
Creates a scatter plot to compare two indicators over multiple years, including a linear regression line and a diagonal reference line. The plot is faceted by year, and displays R-squared values for each year to assess the relationship between indicators.
## S3 method for class 'cd_data' plot_comparison( .data, x_var, y_var, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, call = caller_env(), options = NULL )## S3 method for class 'cd_data' plot_comparison( .data, x_var, y_var, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, call = caller_env(), options = NULL )
.data |
A |
x_var |
Character. Name of the variable to plot on the x-axis (e.g., 'anc1'). |
y_var |
Character. Name of the variable to plot on the y-axis (e.g., 'penta1'). |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional named list or vector overriding the legend labels.
Recognised names are |
call |
The calling environment. |
options |
A |
This function calculates R-squared values for each year and displays them in each facet, helping assess the relationship between the two indicators over time. The diagonal reference line is added to aid in visualizing deviations from a perfect 1:1 relationship.
Common indicator comparisons include:
ANC1 vs PENTA1
PENTA1 vs PENTA3
OPV1 vs OPV3
A ggplot2 object showing the comparison plot of two indicators with linear regression and R-squared values.
## Not run: plot_comparison(cd_data, x_var = "anc1", y_var = "penta1") ## End(Not run)## Not run: plot_comparison(cd_data, x_var = "anc1", y_var = "penta1") ## End(Not run)
Draws one line with points for each of several columns of a data frame against a shared x column, in the package's plot theme. The y axis is scaled to the data: it starts at zero when all values are positive and leaves some room above the highest value.
plot_line_graph( .data, x, y_vars, title, y_title, x_title, legend_labels, hline = NULL, hline_style = "dashed", options = NULL, ... )plot_line_graph( .data, x, y_vars, title, y_title, x_title, legend_labels, hline = NULL, hline_style = "dashed", options = NULL, ... )
.data |
A data frame. |
x |
The column name for the x-axis (e.g., "year"). |
y_vars |
Vector of column names for the y-axis data. |
title |
Plot title. |
y_title |
Label for the y-axis. |
x_title |
Label for the x-axis. |
legend_labels |
Vector of labels for the legend (must match y_vars length). |
hline |
Optional numeric value for a horizontal reference line. |
hline_style |
Style of the horizontal line. |
options |
(Optional) A |
... |
Chart options (see |
A ggplot object.
births <- data.frame( year = 2019:2023, un = c(1445, 1451, 1469, 1483, 1500), dhis2 = c(1390, 1402, 1455, 1478, 1461) ) plot_line_graph(births, x = "year", y_vars = c("un", "dhis2"), title = "Live births (thousands)", y_title = "Live births", x_title = "Year", legend_labels = c("UN estimate", "DHIS2")) plot_line_graph(births, x = "year", y_vars = c("un", "dhis2"), title = "Live births (thousands)", y_title = "Live births", x_title = "Year", legend_labels = c("UN estimate", "DHIS2"), hline = 1500, legend_position = "right")births <- data.frame( year = 2019:2023, un = c(1445, 1451, 1469, 1483, 1500), dhis2 = c(1390, 1402, 1455, 1478, 1461) ) plot_line_graph(births, x = "year", y_vars = c("un", "dhis2"), title = "Live births (thousands)", y_title = "Live births", x_title = "Year", legend_labels = c("UN estimate", "DHIS2")) plot_line_graph(births, x = "year", y_vars = c("un", "dhis2"), title = "Live births (thousands)", y_title = "Live births", x_title = "Year", legend_labels = c("UN estimate", "DHIS2"), hline = 1500, legend_position = "right")
Draws one institutional mortality indicator by year, with a point for each admin level 1 unit, the median of the units in each year and the range of values considered plausible for the indicator. Use it to see whether subnational values are realistic.
plot_mortality_plausibility( x, indicator = c("fresh_total_sb", "ratio_md_sb", "ratio_md_nd"), title = NULL, y_title = NULL, x_title = NULL, caption = NULL, legend_labels = NULL )plot_mortality_plausibility( x, indicator = c("fresh_total_sb", "ratio_md_sb", "ratio_md_nd"), title = NULL, y_title = NULL, x_title = NULL, caption = NULL, legend_labels = NULL )
x |
A |
indicator |
One of |
title |
(Optional) Custom translated title. |
y_title |
(Optional) Custom translated y-axis label. |
x_title |
(Optional) Custom translated x-axis label. |
caption |
(Optional) Custom translated footnote. |
legend_labels |
(Optional) A named list to override default legend labels (keys: 'median', 'plausible'). |
A ggplot object. The function stops with an error when x has no subnational values
for the indicator.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() mortality <- cache$mortality_summary plot_mortality_plausibility(mortality, indicator = "fresh_total_sb") plot_mortality_plausibility(mortality, indicator = "ratio_md_sb", title = "Stillbirths per maternal death", x_title = "Year", legend_labels = list(median = "Median of the regions"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() mortality <- cache$mortality_summary plot_mortality_plausibility(mortality, indicator = "fresh_total_sb") plot_mortality_plausibility(mortality, indicator = "ratio_md_sb", title = "Stillbirths per maternal death", x_title = "Year", legend_labels = list(median = "Median of the regions"))
Creates a horizontal bar plot for either health system performance or density metrics at national level.
plot_national_health_metric(.data, metric = c("performance", "density"))plot_national_health_metric(.data, metric = c("performance", "density"))
.data |
A one-row data frame containing national-level metrics. |
metric |
Either 'performance' or 'density'. |
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() national <- cache$health_system_metrics_national plot_national_health_metric(national, metric = "performance") plot_national_health_metric(national, metric = "density")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() national <- cache$health_system_metrics_national plot_national_health_metric(national, metric = "performance") plot_national_health_metric(national, metric = "density")
plot.cd_adjustment_values_filtered creates a bar plot to compare the unadjusted (raw)
and adjusted values of health indicators over time. It allows users to specify
the indicator prefix and customize legend labels for flexibility across different
health data.
## S3 method for class 'cd_adjustment_values_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, type = c("stacked", "change", "totals"), zoom = TRUE, options = NULL )## S3 method for class 'cd_adjustment_values_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, type = c("stacked", "change", "totals"), zoom = TRUE, options = NULL )
x |
A data frame containing the |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
A named list or vector of custom legend labels, with
names |
type |
With the adjustment's steps in |
zoom |
|
options |
A |
This function helps visualize the difference between raw and adjusted values of a given health indicator, aiding in the assessment of data completeness and adjustments. The difference and percentage difference are calculated within the function but are not directly shown on the plot. Instead, the plot shows the actual unadjusted and adjusted values side-by-side for each year.
A ggplot2 object showing the comparison of unadjusted and adjusted data for the specified indicator over time.
## Not run: # Using default legend labels and title plot.cd_adjustment_values_filtered(adjustments, indicator = "ideliv") # Custom legend labels and title plot.cd_adjustment_values_filtered(adjustments, indicator = "instlivebirths", title = "Customized Title", legend_labels = c("Original", "Modified") ) ## End(Not run)## Not run: # Using default legend labels and title plot.cd_adjustment_values_filtered(adjustments, indicator = "ideliv") # Custom legend labels and title plot.cd_adjustment_values_filtered(adjustments, indicator = "instlivebirths", title = "Customized Title", legend_labels = c("Original", "Modified") ) ## End(Not run)
Visualizes reporting rates for selected health service indicators at sub-national levels,
using heat maps or bar plots. Intended for use with outputs from
calculate_average_reporting_rate() at "adminlevel_1" or "district" level.
## S3 method for class 'cd_average_reporting_rate' plot( x, plot_type = c("heat_map", "bar"), indicator = c("anc_rr", "idelv_rr", "vacc_rr", "opd_rr", "ipd_rr"), threshold = .cd_method$data_quality$reporting_threshold, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_average_reporting_rate' plot( x, plot_type = c("heat_map", "bar"), indicator = c("anc_rr", "idelv_rr", "vacc_rr", "opd_rr", "ipd_rr"), threshold = .cd_method$data_quality$reporting_threshold, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
plot_type |
Either
|
indicator |
One of the following:
|
threshold |
Numeric value (default = 90). Used only in |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
Only subnational objects are accepted. If the data was computed at "adminlevel_1" with a
region argument, the object is automatically treated as "district" level and plotted
by district name.
Heat Map Mode:
Each tile represents a reporting rate for a unit and year.
Colors:
Green: >= threshold
Orange: 70 <= value < threshold
Red: < 70
Labels display the actual percentage.
Bar Mode:
Bars show values per year.
Units (regions or districts) appear as facets.
Color gradient shows low to high reporting.
A ggplot object.
## Not run: # Heat map for vaccination at district level x <- calculate_average_reporting_rate(data, admin_level = "district") plot(x, plot_type = "heat_map", indicator = "vacc_rr") # Bar chart by district in selected region x <- calculate_average_reporting_rate(data, admin_level = "adminlevel_1", region = "Nairobi") plot(x, plot_type = "bar", indicator = "idelv_rr") ## End(Not run)## Not run: # Heat map for vaccination at district level x <- calculate_average_reporting_rate(data, admin_level = "district") plot(x, plot_type = "heat_map", indicator = "vacc_rr") # Bar chart by district in selected region x <- calculate_average_reporting_rate(data, admin_level = "adminlevel_1", region = "Nairobi") plot(x, plot_type = "bar", indicator = "idelv_rr") ## End(Not run)
Leverages the bayescoveragemodel package's internal plotting function and applies the custom Countdown (CD) theme and translated labels.
## S3 method for class 'cd_bayes_model' plot( x, region = NULL, year = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., national = NULL, legend_labels = NULL, options = NULL )## S3 method for class 'cd_bayes_model' plot( x, region = NULL, year = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., national = NULL, legend_labels = NULL, options = NULL )
x |
An object of class |
region |
(Optional) A region of a sub-national model: its estimates by year are drawn, as a national
model's are. |
year |
(Optional) For a sub-national model. The year the regions are compared in; by default the latest
year the facility data has. With a |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
national |
(Optional) For a sub-national model. The country's coverage from the facility data, with the
same denominator: a data frame with |
legend_labels |
(Optional) A named list to override the legend's entries, e.g. with translations: |
options |
A |
A ggplot object with the chart options applied. For a national model, or the region of a
sub-national model: the estimated coverage by year. For a sub-national model with no region: the regions
compared in year, each with its model estimate and interval and its facility-data value.
## Not run: # `cache` is a dataset with adjusted data; fitting needs the Bayesian model packages national <- cache$get_bayes_model("national", "penta3") plot(national) plot(national, title = "Penta3 coverage, Kenya", y_title = "Coverage") # a sub-national model: the regions compared, or the trend of one region regional <- cache$get_bayes_model("adminlevel_1", "penta3") country <- cache$bayes_national_routine("penta3") plot(regional, national = country) plot(regional, year = 2021, national = country) plot(regional, region = "Nairobi", national = country) ## End(Not run)## Not run: # `cache` is a dataset with adjusted data; fitting needs the Bayesian model packages national <- cache$get_bayes_model("national", "penta3") plot(national) plot(national, title = "Penta3 coverage, Kenya", y_title = "Coverage") # a sub-national model: the regions compared, or the trend of one region regional <- cache$get_bayes_model("adminlevel_1", "penta3") country <- cache$bayes_national_routine("penta3") plot(regional, national = country) plot(regional, year = 2021, national = country) plot(regional, region = "Nairobi", national = country) ## End(Not run)
Draws the share of missing values in a completeness summary as a heat map by unit, for one
indicator by year or for all indicators averaged over the years. With plot_type = "trend" it
draws the completeness of one indicator over time, one panel per unit.
## S3 method for class 'cd_completeness_summary' plot( x, plot_type = c("heat_map", "trend"), indicator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., indicator_labels = NULL, options = NULL )## S3 method for class 'cd_completeness_summary' plot( x, plot_type = c("heat_map", "trend"), indicator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., indicator_labels = NULL, options = NULL )
x |
A |
plot_type |
Either |
indicator |
Optional. One of the supported indicators ( |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
indicator_labels |
(Optional) A named vector or list, indicator code -> label, for the axis that names
indicators (see |
options |
A |
A ggplot object: a heat map or a faceted line chart, depending on plot_type.
## Not run: # Region-level summary plot(missing_data, indicator = "penta3") ## End(Not run)## Not run: # Region-level summary plot(missing_data, indicator = "penta3") ## End(Not run)
Generates a bar chart comparing indicator coverage across regions, highlighting a specific region and categorizing performance as lower, average, or higher.
## S3 method for class 'cd_coverage' plot( x, indicator = NULL, denominator = NULL, year = NULL, region = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_coverage' plot( x, indicator = NULL, denominator = NULL, year = NULL, region = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
Data frame containing the coverage data. |
indicator |
Character string specifying the indicator (e.g., 'penta1'). |
denominator |
Character string specifying the denominator ('penta1', 'anc1', 'dhis2', 'penta1derived', 'anc1derived'). |
year |
Integer representing the year to plot. |
region |
Character string for the specific region to highlight in yellow. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) Named list to override the default category labels
(e.g., |
options |
A |
A ggplot object with the chart options applied: one bar per unit for the selected year,
ordered by coverage and coloured by category (the lower, middle and upper third of the values).
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$calculate_coverage("adminlevel_1") # `region` is the unit drawn in yellow plot(coverage, indicator = "penta3", denominator = "penta1", year = 2023, region = "Nairobi") plot(coverage, indicator = "penta3", denominator = "penta1", year = 2023, region = "Nairobi", title = "Penta3 coverage by region, 2023", y_title = "Coverage (%)", legend_labels = list(lower = "Lowest third", average = "Middle third", higher = "Highest third"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$calculate_coverage("adminlevel_1") # `region` is the unit drawn in yellow plot(coverage, indicator = "penta3", denominator = "penta1", year = 2023, region = "Nairobi") plot(coverage, indicator = "penta3", denominator = "penta1", year = 2023, region = "Nairobi", title = "Penta3 coverage by region, 2023", y_title = "Coverage (%)", legend_labels = list(lower = "Lowest third", average = "Middle third", higher = "Highest third"))
Generates a line plot to visualize immunization coverage data across years, allowing comparison between different estimates (e.g., DHIS2 estimates, WUENIC estimates, and Survey estimates).
## S3 method for class 'cd_coverage_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_coverage_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A data frame of type |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list or vector to override the legend keys for translation.
Valid keys: |
options |
A |
A ggplot object displaying a line plot of the coverage data.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$get_filtered_coverage("penta3", "national") plot(coverage) plot(coverage, title = "Penta3 coverage, Kenya", y_title = "Coverage (%)", legend_labels = list(dhis2 = "Facility data", survey = "Household surveys"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() coverage <- cache$get_filtered_coverage("penta3", "national") plot(coverage) plot(coverage, title = "Penta3 coverage, Kenya", y_title = "Coverage (%)", legend_labels = list(dhis2 = "Facility data", survey = "Household surveys"))
Draws the latest coverage of a set of indicators. National data, or the data of one region, is drawn as a profile (bars by indicator and source) or as the gap between the facility and the survey estimate. Subnational data is drawn as dots by unit, one panel per indicator, or as a heatmap of units by indicator.
## S3 method for class 'cd_coverage_selected' plot( x, type = NULL, source_labels = NULL, indicator_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_coverage_selected' plot( x, type = NULL, source_labels = NULL, indicator_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
An object of class |
type |
"profile" or "gap" (for national), "dot" or "heatmap" (for subnational). |
source_labels |
(Optional) Named list to translate 'facility', 'survey', 'wuenic'. |
indicator_labels |
(Optional) Named list to translate indicator names (e.g. 'anc4'). |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object with the chart options applied. Which chart it is depends on type
and on the admin level of x.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # national: a profile of the indicators, or the gap between facility data and the survey national <- cache$generate_coverage_data("national", "maternal") plot(national, type = "profile") plot(national, type = "gap", title = "Facility data against the survey", legend_position = "bottom") # by region: a heatmap (or "dot") regions <- cache$generate_coverage_data("adminlevel_1", "child") plot(regions, type = "heatmap", legend_title = "Coverage (%)")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # national: a profile of the indicators, or the gap between facility data and the survey national <- cache$generate_coverage_data("national", "maternal") plot(national, type = "profile") plot(national, type = "gap", title = "Facility data against the survey", legend_position = "bottom") # by region: a heatmap (or "dot") regions <- cache$generate_coverage_data("adminlevel_1", "child") plot(regions, type = "heatmap", legend_title = "Coverage (%)")
Generates a line plot comparing traditional (coverage_old)
and derived (coverage_new) coverage estimates over time for a single indicator.
It supports both national and subnational views.
## S3 method for class 'cd_derived_coverage' plot( x, type = c("bar", "trend"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = list(), options = NULL )## S3 method for class 'cd_derived_coverage' plot( x, type = c("bar", "trend"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = list(), options = NULL )
x |
A |
type |
A character string specifying the plot type: |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list of character strings to override specific
default legend labels (e.g., |
options |
A |
A ggplot object showing coverage trends over time.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() derived <- cache$calculate_derived_coverage("penta3", "national") plot(derived) plot(derived, type = "trend", title = "Penta3: usual and derived denominators", y_title = "Coverage (%)", legend_position = "bottom")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() derived <- cache$calculate_derived_coverage("penta3", "national") plot(derived) plot(derived, type = "trend", title = "Penta3: usual and derived denominators", y_title = "Coverage (%)", legend_position = "bottom")
Generates a bar plot displaying the percentage of districts with reporting rates below the defined threshold for multiple indicators across various years. This plot provides a quick visual assessment of district-level reporting compliance across indicators like ANC, Institutional Delivery, PNC, Vaccination, OPD, and IPD.
## S3 method for class 'cd_district_reporting_rate' plot( x, indicator_labels = NULL, facet_ncol = 3, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_district_reporting_rate' plot( x, indicator_labels = NULL, facet_ncol = 3, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
indicator_labels |
Optional named character vector of panel titles,
keyed by short indicator name ( |
facet_ncol |
Integer. The number of columns the service panels are laid out in. Default is |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
Inverts the percentages in x (the percentage of districts at or above the threshold) to
display the percentage of districts with rates below the threshold for each indicator (e.g.,
if 95% of districts reach the threshold, 5% are shown as below it). Each indicator is visualized
in a separate panel with data grouped by year, providing an overview of performance
trends over time.
Indicators plotted include:
Antenatal Care (ANC) - Percentage of districts meeting or exceeding target rates
Institutional Delivery - Institutional delivery compliance over time
Postnatal Care (PNC) - Districts' PNC service rates against thresholds
Vaccination - Vaccination service coverage at district level
Outpatient Department (OPD) - OPD reporting rates in districts
Inpatient Department (IPD) - IPD reporting compliance by district
The plot output includes a title, axis labels, and a legend for year, allowing users to identify service areas with low reporting compliance.
A ggplot object visualizing reporting rates across indicators and years.
## Not run: # Generate a plot of district reporting rates below a threshold of 90% plot(cd_district_reporting_rate(data), threshold = 90) ## End(Not run)## Not run: # Generate a plot of district reporting rates below a threshold of 90% plot(cd_district_reporting_rate(data), threshold = 90) ## End(Not run)
Generates a line and ribbon plot for FPET indicators (e.g., mCPR, Demand Satisfied) displaying median estimates and 95% credible intervals.
## S3 method for class 'cd_fpet_data' plot( x, indicator_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_fpet_data' plot( x, indicator_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
An object of class |
indicator_labels |
(Optional) A named list mapping raw indicator names to translated legend labels. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object with the chart options applied: one line per indicator by year, with a
shaded band for the credible interval.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) fpet <- cache$fpet_data plot(fpet) plot( fpet, indicator_labels = list(prevalence = "Modern contraceptive prevalence", demand = "Demand satisfied"), title = "Family planning in Kenya" )path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) fpet <- cache$fpet_data plot(fpet) plot( fpet, indicator_labels = list(prevalence = "Modern contraceptive prevalence", demand = "Demand satisfied"), title = "Family planning in Kenya" )
Generates scatterplots with linear fit and identity line comparing district to admin level 1 metrics or coverage vs density.
## S3 method for class 'cd_health_system_comparison' plot( x, indicator = c("cov_instdeliveries_hstaff", "ratio_opd_u5_hstaff", "ratio_ipd_u5_hos", "ratio_ipd_u5_bed"), denominator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_health_system_comparison' plot( x, indicator = c("cov_instdeliveries_hstaff", "ratio_opd_u5_hstaff", "ratio_ipd_u5_hos", "ratio_ipd_u5_bed"), denominator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A data frame from |
indicator |
One of ratio_* or cov_instdeliveries_* (requires |
denominator |
Optional for cov_ indicators. Must be one of 'dhis2', 'anc1', 'penta1'. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list to override default legend labels (keys: 'admin', 'linear'). |
options |
A |
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() comparison <- cache$health_system_comparison plot(comparison, indicator = "ratio_opd_u5_hstaff") plot(comparison, indicator = "ratio_ipd_u5_bed", title = "Admissions of children and hospital beds", legend_labels = list(admin = "Regions", linear = "Trend"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() comparison <- cache$health_system_comparison plot(comparison, indicator = "ratio_opd_u5_hstaff") plot(comparison, indicator = "ratio_ipd_u5_bed", title = "Admissions of children and hospital beds", legend_labels = list(admin = "Regions", linear = "Trend"))
Plots individual health system indicators by admin level 1 and compares with national value or target.
## S3 method for class 'cd_health_system_metric' plot( x, indicator = c("ratio_fac_pop", "ratio_hos_pop", "ratio_bed_pop", "ratio_hstaff_pop", "skill_mix"), national_value = NA_real_, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_health_system_metric' plot( x, indicator = c("ratio_fac_pop", "ratio_hos_pop", "ratio_bed_pop", "ratio_hstaff_pop", "skill_mix"), national_value = NA_real_, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
Data frame containing admin level 1 indicators. |
indicator |
A single metric to plot. Options include ratio_fac_pop, ratio_hos_pop, ratio_bed_pop, ratio_hstaff_pop, skill_mix. |
national_value |
A numeric value representing the national average to plot as a vertical line. Can be NA. |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list to override default legend labels (e.g. for translation). |
options |
A |
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() regions <- cache$health_system_metrics_admin1 national <- cache$health_system_metrics_national plot(regions, indicator = "ratio_fac_pop", national_value = national$ratio_fac_pop) plot(regions, indicator = "ratio_hstaff_pop", national_value = national$ratio_hstaff_pop, title = "Health workers per 10,000 people", x_title = "Health workers", legend_labels = list(threshold_line = "Benchmark (44.5)"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() regions <- cache$health_system_metrics_admin1 national <- cache$health_system_metrics_national plot(regions, indicator = "ratio_fac_pop", national_value = national$ratio_fac_pop) plot(regions, indicator = "ratio_hstaff_pop", national_value = national$ratio_hstaff_pop, title = "Health workers per 10,000 people", x_title = "Health workers", legend_labels = list(threshold_line = "Benchmark (44.5)"))
Draws the national health system metrics as a formatted table. The indicators are grouped under their section, each with its value and unit, and the year is shown in a line above the column headers.
## S3 method for class 'cd_health_system_table' plot( x, year = 2024, width = NULL, indicator_label = "Indicator", value_label = "Value", unit_label = "Unit", ..., options = NULL )## S3 method for class 'cd_health_system_table' plot( x, year = 2024, width = NULL, indicator_label = "Indicator", value_label = "Value", unit_label = "Unit", ..., options = NULL )
x |
An object of class |
year |
The year to display in the header (defaults to 2024) |
width |
(Optional) Total width in inches. If NULL, autofit is used. |
indicator_label |
(Optional) Translated label for the Indicator column header |
value_label |
(Optional) Translated label for the Value column header |
unit_label |
(Optional) Translated label for the Unit column header |
... |
Additional arguments |
options |
(Optional) A |
A flextable object (from the flextable package), not a ggplot. Chart options change
ggplots only, so options has no effect on this table.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() metrics <- cache$generate_health_system_table() plot(metrics, year = 2023) plot(metrics, year = 2023, width = 6, indicator_label = "Indicateur", value_label = "Valeur", unit_label = "Unite")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() metrics <- cache$generate_health_system_table() plot(metrics, year = 2023) plot(metrics, year = 2023, width = 6, indicator_label = "Indicateur", value_label = "Valeur", unit_label = "Unite")
Generates specific plots for national denominators and health coverage indicators. It supports dynamic customization of titles and labels.
## S3 method for class 'cd_indicator_coverage' plot( x, plot_type = c("anc_coverage_dhis2", "delivery_coverage_dhis2", "immunization_coverage_dhis2", "anc_coverage_un", "delivery_coverage_un", "immunization_coverage_un", "anc_coverage_anc1", "delivery_coverage_anc1", "immunization_coverage_anc1", "anc_coverage_penta1", "delivery_coverage_penta1", "immunization_coverage_penta1"), admin_name = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_indicator_coverage' plot( x, plot_type = c("anc_coverage_dhis2", "delivery_coverage_dhis2", "immunization_coverage_dhis2", "anc_coverage_un", "delivery_coverage_un", "immunization_coverage_un", "anc_coverage_anc1", "delivery_coverage_anc1", "immunization_coverage_anc1", "anc_coverage_penta1", "delivery_coverage_penta1", "immunization_coverage_penta1"), admin_name = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
plot_type |
Character. The specific indicator set to plot. Valid options include:
|
admin_name |
Optional character. The specific admin area to filter by (required if data is subnational). |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional character vector. Custom labels for the legend items. Must match the number of lines in the selected plot type. |
options |
A |
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() plot(cache$indicator_coverage_national, plot_type = "anc_coverage_penta1") plot(cache$indicator_coverage_national, plot_type = "immunization_coverage_dhis2", title = "Immunization coverage, DHIS2 population", y_title = "Coverage (%)", legend_position = "right") # subnational data: name the unit plot(cache$indicator_coverage_admin1, plot_type = "immunization_coverage_dhis2", admin_name = "Nairobi")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() plot(cache$indicator_coverage_national, plot_type = "anc_coverage_penta1") plot(cache$indicator_coverage_national, plot_type = "immunization_coverage_dhis2", title = "Immunization coverage, DHIS2 population", y_title = "Coverage (%)", legend_position = "right") # subnational data: name the unit plot(cache$indicator_coverage_admin1, plot_type = "immunization_coverage_dhis2", admin_name = "Nairobi")
Generates a plot to visualize health coverage data across subnational units, distinguishing between the national mean and subnational coverage. The Mean Absolute Difference to the Mean (MADM) is displayed as an indicator on the y-axis.
## S3 method for class 'cd_inequality_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_inequality_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list or vector to override the legend keys and MADM label for translation.
Valid keys: |
options |
A |
A ggplot object displaying the subnational health coverage plot.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() inequality <- cache$get_filtered_inequality("penta3", "adminlevel_1") plot(inequality) plot(inequality, title = "Penta3 coverage by region", y_title = "Coverage (%)", legend_labels = list(subnational = "Regions", national = "Kenya"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() inequality <- cache$get_filtered_inequality("penta3", "adminlevel_1") plot(inequality) plot(inequality, title = "Penta3 coverage by region", y_title = "Coverage (%)", legend_labels = list(subnational = "Regions", national = "Kenya"))
Creates a faceted ggplot2 map showing subnational coverage levels of a health indicator,
colored using a gradient palette. Coverage values are drawn from a cd_mapping_filtered
object, typically filtered for a specific indicator and denominator.
## S3 method for class 'cd_mapping_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_mapping_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object visualizing the spatial distribution of the selected indicator by region and year.
select_mapping_data(), get_mapping_data()
## Not run: # Assuming `map_data` is filtered with select_mapping_data() plot( map_data, title = "Penta 1 Coverage by Region", legend = "Coverage (%)", caption = "Source: DHIS2 2024" ) ## End(Not run)## Not run: # Assuming `map_data` is filtered with select_mapping_data() plot( map_data, title = "Penta 1 Coverage by Region", legend = "Coverage (%)", caption = "Source: DHIS2 2024" ) ## End(Not run)
Draws a scatter plot of the curative services index against the MCH preventive services index, with one point per admin level 1 unit. Dashed lines at the two medians split the plot into four labelled quadrants, and the units with the highest and lowest value of either index are named.
## S3 method for class 'cd_mch_curative_index' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., quad_labels = NULL, options = NULL )## S3 method for class 'cd_mch_curative_index' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., quad_labels = NULL, options = NULL )
x |
Object of class cd_mch_curative_index, as returned by
|
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
quad_labels |
(Optional) A named list of the texts written in the four quadrants: |
options |
A |
A ggplot object, with the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() index <- cache$generate_admin1_mch_curative_index() plot(index) plot(index, title = "Preventive and curative care", x_title = "Preventive index", y_title = "Curative index", quad_labels = list(q_top_right = "High on both", q_bottom_left = "Low on both"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() index <- cache$generate_admin1_mch_curative_index() plot(index) plot(index, title = "Preventive and curative care", x_title = "Preventive index", y_title = "Curative index", quad_labels = list(q_top_right = "High on both", q_bottom_left = "Low on both"))
Visualizes the percentage of districts with complete data for a selected indicator over time.
## S3 method for class 'cd_missing_district' plot( x, indicator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_missing_district' plot( x, indicator = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
indicator |
A character string specifying the indicator to plot.
Must be one of the values returned by |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
The function produces a column chart showing the percent of districts with complete data for the selected indicator by year.
A ggplot object.
## Not run: plot(missing_summary, indicator = "penta1") ## End(Not run)## Not run: plot(missing_summary, indicator = "penta1") ## End(Not run)
Calculates and plots the estimated completeness of facility reporting for maternal deaths or stillbirths based on UN estimates and assumed community-to-institution ratios.
## S3 method for class 'cd_mortality_ratio_summarised' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_mortality_ratio_summarised' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list to override the legend's entries, e.g. with translations: |
options |
A |
A ggplot object with ratio lines, labels, and reference points.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() completeness <- cache$summarise_completeness_ratio("mmr") plot(completeness) plot(completeness, title = "Completeness of maternal death reporting", y_title = "Completeness (%)", legend_labels = list(lower = "UN lower bound", best = "UN best estimate", upper = "UN upper bound"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() completeness <- cache$summarise_completeness_ratio("mmr") plot(completeness) plot(completeness, title = "Completeness of maternal death reporting", y_title = "Completeness (%)", legend_labels = list(lower = "UN lower bound", best = "UN best estimate", upper = "UN upper bound"))
Produces line plots for national mortality indicators with regional points for comparison.
## S3 method for class 'cd_mortality_summary' plot( x, indicator = c("mmr_inst", "ratio_md_sb", "sbr_inst", "nn_inst"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_mortality_summary' plot( x, indicator = c("mmr_inst", "ratio_md_sb", "sbr_inst", "nn_inst"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
indicator |
One of |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list to override the legend's entries, e.g. with translations: |
options |
A |
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() mortality <- cache$mortality_summary plot(mortality, indicator = "mmr_inst") plot(mortality, indicator = "sbr_inst", title = "Institutional stillbirth rate", legend_labels = list(national = "Kenya", regions = "Regions"), legend_position = "bottom")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() mortality <- cache$mortality_summary plot(mortality, indicator = "mmr_inst") plot(mortality, indicator = "sbr_inst", title = "Institutional stillbirth rate", legend_labels = list(national = "Kenya", regions = "Regions"), legend_position = "bottom")
Visualizes institutional mortality rates (MMR or SBR) across regions using filled
geographic polygons. Facets the map by year and applies a color gradient by value.
## S3 method for class 'cd_mortality_summary_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_mortality_summary_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
Takes the default title and legend title from the indicator attribute of x and sets the
geometry to WGS84 coordinates. Draws the regions as filled polygons with geom_sf(), one panel
per year, on a sequential colour scale from the palette stored on x (Reds by default), with
gray for missing values.
A ggplot2 object: the map, with the chart options applied.
## Not run: filtered <- select_mortality_summary(mortality_data, "UGA", indicator = "mmr", plot_year = 2020:2022) plot(filtered) ## End(Not run)## Not run: filtered <- select_mortality_summary(mortality_data, "UGA", indicator = "mmr", plot_year = 2020:2022) plot(filtered) ## End(Not run)
Plots annual trends or heat maps of non-outlier rates for immunization indicators at subnational levels.
## S3 method for class 'cd_outlier' plot( x, selection_type = c("region", "indicator", "heat_map"), indicator = NULL, threshold = .cd_method$data_quality$reporting_threshold, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., indicator_labels = NULL, options = NULL )## S3 method for class 'cd_outlier' plot( x, selection_type = c("region", "indicator", "heat_map"), indicator = NULL, threshold = .cd_method$data_quality$reporting_threshold, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., indicator_labels = NULL, options = NULL )
x |
A |
selection_type |
One of
|
indicator |
Optional. Specific indicator name (e.g., |
threshold |
Numeric. Upper cut-off (in percent) of the middle colour
band; values above it are shown as good. Default is |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
indicator_labels |
(Optional) A named vector or list, indicator code -> label, for the axis that names
indicators (see |
options |
A |
Values are assumed to be percentages of non-outliers (i.e., 100 = no outliers).
"region" and "indicator" use bar plots with gradient fill.
"heat_map" shows indicator values by year and region.
A ggplot object.
## Not run: plot(outlier_data, selection_type = "region", indicator = "penta3") plot(outlier_data, selection_type = "heat_map") ## End(Not run)## Not run: plot(outlier_data, selection_type = "region", indicator = "penta3") plot(outlier_data, selection_type = "heat_map") ## End(Not run)
Displays a time-series plot of one indicator for a single region or district, with outlier highlights.
## S3 method for class 'cd_outlier_list' plot( x, indicator = NULL, year = NULL, region = NULL, label = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_outlier_list' plot( x, indicator = NULL, year = NULL, region = NULL, label = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
indicator |
The indicator to plot (for example |
year |
Optional single year to plot. If |
region |
The name of the unit to plot. |
label |
Optional named character vector overriding the legend labels.
Recognised names are |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
Plots observed values, median trend, and 5xMAD range.
Flags outliers in red.
A ggplot object.
## Not run: list_outlier_units(cd_data, "penta1") %>% plot(region_name = "Nakuru") ## End(Not run)## Not run: list_outlier_units(cd_data, "penta1") %>% plot(region_name = "Nakuru") ## End(Not run)
Draws the overall data quality score as a formatted table, with the metrics grouped by type and a column for each year. Percentage scores are shaded green at or above the threshold stored with the scores, yellow from 70 up to the threshold and red below 70.
## S3 method for class 'cd_overall_score' plot(x, years = NULL, title = NULL, width = NULL, ..., options = NULL)## S3 method for class 'cd_overall_score' plot(x, years = NULL, title = NULL, width = NULL, ..., options = NULL)
x |
The score dataframe (class |
years |
Vector of years to display. Required: each must be a year column of |
title |
(Optional) Custom title for the table |
width |
(Optional) Total width in inches. If NULL, autofit is used. |
... |
Additional arguments |
options |
(Optional) A |
A flextable object (from the flextable package), not a ggplot. Chart options change
ggplots only, so options has no effect on this table.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) score <- calculate_overall_score(data, threshold = 90) plot(score, years = 2019:2023) plot(score, years = 2021:2023, title = "Data quality, last three years", width = 7)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) score <- calculate_overall_score(data, threshold = 90) plot(score, years = 2019:2023) plot(score, years = 2021:2023, title = "Data quality, last three years", width = 7)
Draws a scatter plot of the service coverage index against facility density or health workforce density, with one point per admin level 1 unit. Dashed lines at the two medians split the plot into four labelled quadrants, and the units flagged as outliers are named.
## S3 method for class 'cd_phc_scatter' plot( x, quad_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_phc_scatter' plot( x, quad_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
An object of class |
quad_labels |
(Optional) Named list to override quadrant text.
Expected keys: |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object, with the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() scatter <- cache$generate_phc_scatter_data("ratio_fac_pop") plot(scatter) plot(scatter, title = "Facilities and services by region", y_title = "Service index", quad_labels = list(low_low = "Few facilities, few services"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() scatter <- cache$generate_phc_scatter_data("ratio_fac_pop") plot(scatter) plot(scatter, title = "Facilities and services by region", y_title = "Service index", quad_labels = list(low_low = "Few facilities, few services"))
Generates a line graph to visualize national-level demographic data, comparing DHIS-2 data/projections against UN estimates. This function is restricted to national-level data.
## S3 method for class 'cd_population_metrics' plot( x, metric = c("population", "births", "under1"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_population_metrics' plot( x, metric = c("population", "births", "under1"), title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
metric |
A character string specifying the type of data to plot. Must be one of:
|
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
Optional. A character vector of custom labels for the legend items. Must match the number of lines plotted for the selected metric:
|
options |
A |
The function compares local Health Management Information System (DHIS-2) data with United Nations (UN) estimates.
Default Configuration:
Population: Compares un_population vs totpop_dhis2.
Births: Compares un_births vs totlivebirths_dhis2 vs totbirths_dhis2.
Under 1: Compares un_under1 vs totunder1_dhis2.
A ggplot object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() population <- cache$denominator_metrics plot(population, metric = "population") plot(population, metric = "births", title = "Births: DHIS2 and the UN", y_title = "Thousands", legend_labels = c("UN live births", "DHIS2 live births", "DHIS2 births"))cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() population <- cache$denominator_metrics plot(population, metric = "population") plot(population, metric = "births", title = "Births: DHIS2 and the UN", y_title = "Thousands", legend_labels = c("UN live births", "DHIS2 live births", "DHIS2 births"))
Draws a stacked bar for each admin level 1 unit showing the percentage of health facilities that are private, NGO and public, with the percentage written inside each segment.
## S3 method for class 'cd_private_sector' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_private_sector' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
An object of class |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object, with the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() ownership <- cache$generate_private_sector_data() plot(ownership) plot(ownership, title = "Who owns the health facilities", y_title = "Facilities (%)", legend_title = "Owner", legend_position = "right")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() ownership <- cache$generate_private_sector_data() plot(ownership) plot(ownership, title = "Who owns the health facilities", y_title = "Facilities (%)", legend_title = "Owner", legend_position = "right")
Generates a stacked bar chart for RMNCAH indicators comparing public vs. private sector share by either national or area-level (urban/rural) estimates.
## S3 method for class 'cd_private_sector_plot_data' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., country_name = NULL, legend_labels = NULL, indicator_labels = NULL, area_labels = NULL, share_label = NULL, options = NULL )## S3 method for class 'cd_private_sector_plot_data' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., country_name = NULL, legend_labels = NULL, indicator_labels = NULL, area_labels = NULL, share_label = NULL, options = NULL )
x |
A data frame of class |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
country_name |
Optional character string to override the default country name used
in the plot title. If |
legend_labels |
(Optional) A named list to override the legend's entries, e.g. with translations: |
indicator_labels |
(Optional) A named list of the indicators' names: |
area_labels |
(Optional) A named list of the areas' names, for area data: |
share_label |
(Optional) The text written before the private share. By default |
options |
A |
The function automatically detects whether the data is at the "national" or "area"
level using the "level" attribute. It:
Maps indicator codes to descriptive labels
Stacks r_raw_Public and r_raw_Private values
Adds text annotations for private sector shares
For area-level data, bars are grouped by area and faceted by indicator.
For national-level data, each indicator has a single stacked bar.
A ggplot object with:
Stacked bars for public/private sector share
Facets by indicator for area-level plots
Annotated private sector shares as text labels
## Not run: dt <- load_private_sector_data("Area estimates.dta", country_iso = "TZA", level = "area") cs <- load_csection_estimates("csection_area.dta", country_iso = "TZA", level = "area") plot_data <- prepare_private_sector_plot_data(dt, cs) plot(plot_data) ## End(Not run)## Not run: dt <- load_private_sector_data("Area estimates.dta", country_iso = "TZA", level = "area") cs <- load_csection_estimates("csection_area.dta", country_iso = "TZA", level = "area") plot_data <- prepare_private_sector_plot_data(dt, cs) plot(plot_data) ## End(Not run)
Generates a bar plot for a cd_ratios_summary object,
displaying the calculated indicator ratios for each year. It allows
for visual comparison across years, showing how each indicator ratio
changes over time.
## S3 method for class 'cd_ratios_summary' plot( x, x_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_ratios_summary' plot( x, x_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
x_labels |
Optional named list or vector of x-axis category labels,
keyed by ratio name ( |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
This function provides a visual summary of indicator ratios, with each ratio displayed
as a bar for each year. The Expected Ratio row is included if available, allowing
for easy comparison of actual ratios against expected values. The bars are grouped
by year, with distinct colors representing each year for clear differentiation.
A ggplot object representing a bar plot of indicator ratios by year.
## Not run: # Assuming `cd_ratios_summary` is the object returned by `calculate_ratios_summary` plot(cd_ratios_summary) ## End(Not run)## Not run: # Assuming `cd_ratios_summary` is the object returned by `calculate_ratios_summary` plot(cd_ratios_summary) ## End(Not run)
Draws a horizontal bar for each admin level 1 unit showing its under-five OPD visits per child or IPD admissions per 100 children in the latest year. The bars are ordered by value and labelled with it.
## S3 method for class 'cd_service_utilization_admin1' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_service_utilization_admin1' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
Object of class cd_service_utilization_admin1, as returned by
|
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object, with the chart options applied.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() plot(cache$generate_admin1_service_utilization("opd")) plot(cache$generate_admin1_service_utilization("ipd"), title = "Admissions of children under five", x_title = "Admissions per 100 children", show_legend = FALSE)cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() plot(cache$generate_admin1_service_utilization("opd")) plot(cache$generate_admin1_service_utilization("ipd"), title = "Admissions of children under five", x_title = "Admissions per 100 children", show_legend = FALSE)
Visualizes service utilization over time from a cd_service_utilization_filtered object.
## S3 method for class 'cd_service_utilization_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )## S3 method for class 'cd_service_utilization_filtered' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., legend_labels = NULL, options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
legend_labels |
(Optional) A named list to override the legend's entries, e.g. with translations: |
options |
A |
A ggplot2 plot object.
## Not run: plot(select_service_utilization(dat, indicator = 'opd')) ## End(Not run)## Not run: plot(select_service_utilization(dat, indicator = 'opd')) ## End(Not run)
Generates a faceted map of service utilization metrics across subnational units (admin level 1) for each available year. Uses spatial polygons filled by the selected indicator.
## S3 method for class 'cd_service_utilization_prepared' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_service_utilization_prepared' plot( x, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
Reads the indicator stored on x (ratio_opd_u5_pop or ratio_ipd_u5_pop) and sets the data to
WGS84 coordinates. Draws the units with geom_sf(), filled on a sequential colour scale from the
palette stored on x (purple by default), with one panel per year and the package's map theme.
A ggplot2 object representing faceted service utilization maps by year.
## Not run: plot(filtered) ## End(Not run)## Not run: plot(filtered) ## End(Not run)
Generates a grouped bar chart showing the percentage of administrative regions that meet specific health coverage or dropout thresholds over time.
## S3 method for class 'cd_threshold' plot( x, x_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )## S3 method for class 'cd_threshold' plot( x, x_labels = NULL, title = NULL, subtitle = NULL, caption = NULL, x_title = NULL, y_title = NULL, legend_title = NULL, ..., options = NULL )
x |
A |
x_labels |
(Optional) A named list or vector to translate the raw indicator names
on the x-axis (e.g., |
title |
The chart's title. |
subtitle |
The line under the title. |
caption |
The note under the chart. |
x_title |
The title of the horizontal axis. |
y_title |
The title of the vertical axis. |
legend_title |
The title of the legend. |
... |
Chart options by name (see |
options |
A |
A ggplot object displaying a grouped bar chart of threshold attainment.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() reached <- cache$get_filtered_threshold("vaccine", "district") plot(reached) plot(reached, x_labels = list(bcg = "BCG", penta3 = "Penta 3", measles1 = "Measles 1"), title = "Districts reaching the vaccination target", y_title = "Districts (%)", legend_title = "Year")cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() reached <- cache$get_filtered_threshold("vaccine", "district") plot(reached) plot(reached, x_labels = list(bcg = "BCG", penta3 = "Penta 3", measles1 = "Measles 1"), title = "Districts reaching the vaccination target", y_title = "Districts (%)", legend_title = "Year")
Draws the service utilization data quality summary as a formatted table, with the indicators grouped by section and a column for each year. Completeness and outlier percentages are shaded green at or above the threshold stored with the summary, yellow from 70 up to the threshold and red below 70.
## S3 method for class 'cd_utilization_dqa' plot(x, years = NULL, title = NULL, width = NULL, ..., options = NULL)## S3 method for class 'cd_utilization_dqa' plot(x, years = NULL, title = NULL, width = NULL, ..., options = NULL)
x |
The score dataframe (needs class 'cd_utilization_dqa'), as returned by
|
years |
Vector of years to display (e.g., 2020:2024). Required. |
title |
(Optional) Custom title for the table |
width |
(Optional) Total width in inches. If NULL, autofit is used. |
... |
Additional arguments |
options |
(Optional) A |
A flextable object (from the flextable package), not a ggplot. Chart options change
ggplots only, so options has no effect on this table.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() dqa <- cache$calculate_service_dqa_summary("national") plot(dqa, years = cache$data_years) plot(dqa, years = 2021:2023, title = "Quality of OPD and IPD data", width = 7)cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() dqa <- cache$calculate_service_dqa_summary("national") plot(dqa, years = cache$data_years) plot(dqa, years = 2021:2023, title = "Quality of OPD and IPD data", width = 7)
Selects one under-five indicator from a cd_service_utilization object, optionally for given years.
Joins spatial data for subnational mapping and renames geometry for use with ggplot2::geom_sf().
prepare_mapping_service_utlization( .data, indicator = c("ipd", "opd"), plot_years = NULL, subnational_map = NULL, palette = c("Purples", "Blues", "Greens", "Reds", "YlGnBu") )prepare_mapping_service_utlization( .data, indicator = c("ipd", "opd"), plot_years = NULL, subnational_map = NULL, palette = c("Purples", "Blues", "Greens", "Reds", "YlGnBu") )
.data |
A |
indicator |
Character. Service indicator to map, either |
plot_years |
Optional. Integer or vector of years to include. |
subnational_map |
Optional. A mapping data frame to link |
palette |
Character. RColorBrewer palette name stored on the result for
the map fill: one of |
Selects the under-five service indicator (ratio_ipd_u5_pop or ratio_opd_u5_pop) and joins the
admin level 1 shapefile of the country whose ISO3 code is stored on .data. Keeps only
plot_years when they are given, and renames the geometry column to geometry for geom_sf().
Only adminlevel_1 data is currently supported for mapping.
A tibble of class cd_service_utilization_prepared, ready for faceted spatial plotting.
## Not run: prepare_mapping_service_utlization(service_data, indicator = "opd", plot_years = 2019:2022) ## End(Not run)## Not run: prepare_mapping_service_utlization(service_data, indicator = "opd", plot_years = 2019:2022) ## End(Not run)
prepare_population_metrics calculates demographic metrics such as total
population, live births, growth rates, and related indicators using DHIS-2
population data. For national-level data, it optionally integrates UN estimates
to provide comparative metrics. The function supports aggregation at different
administrative levels, including national, adminlevel_1, and district levels.
prepare_population_metrics( .data, admin_level = c("national", "adminlevel_1", "district"), un_estimates = NULL, region = NULL, show_district = TRUE )prepare_population_metrics( .data, admin_level = c("national", "adminlevel_1", "district"), un_estimates = NULL, region = NULL, show_district = TRUE )
.data |
A |
admin_level |
Character. Specifies the administrative level for aggregation.
Available options are: |
un_estimates |
Optional. A tibble containing UN population estimates with
columns for |
region |
Optional name of an |
show_district |
Logical. When |
A tibble of class cd_population_metrics containing demographic metrics
for the specified administrative level and years. Metrics include:
For all levels: DHIS-2 metrics such as totpop_dhis2 (total population)
and totlivebirths_dhis2 (total live births).
For national level: Both DHIS-2 and UN metrics for comparison.
## Not run: # National-level demographic metrics population_data <- prepare_population_metrics( .data = dhis2_data, admin_level = "national", un_estimates = un_data ) # District-level demographic metrics population_data <- prepare_population_metrics( .data = dhis2_data, admin_level = "district" ) ## End(Not run)## Not run: # National-level demographic metrics population_data <- prepare_population_metrics( .data = dhis2_data, admin_level = "national", un_estimates = un_data ) # District-level demographic metrics population_data <- prepare_population_metrics( .data = dhis2_data, admin_level = "district" ) ## End(Not run)
Processes reshaped private sector data and c-section correction estimates to produce a tidy dataset for plotting public/private sector shares.
prepare_private_sector_plot_data(.data, csection_data)prepare_private_sector_plot_data(.data, csection_data)
.data |
A data frame of class |
csection_data |
A data frame of class |
Joins private sector data with correction estimates using iso, year, and indic (and area
for area data). For "csection" rows, applies the adjustment r_raw = estimate * share_csection.
Drops intermediate columns, reshapes the data to one row per indicator with a set of columns for
each sector, and calculates private sector share and total prevalence.
Used as input to plot.cd_private_sector_plot_data() for visualisation.
A tibble of class "cd_private_sector_plot_data" with attributes:
level: "national" or "area"
Columns reshaped from wide to include r_raw_Public, r_raw_Private, etc.
Computed columns:
privateShare: percent share of private sector
totalPrevalence: total prevalence (public + private)
## Not run: dt <- load_private_sector_data("National estimates.dta", country_iso = "KEN", level = "national") cs <- load_csection_estimates("csection_national.dta", country_iso = "KEN", level = "national") plot_data <- prepare_private_sector_plot_data(dt, cs) ## End(Not run)## Not run: dt <- load_private_sector_data("National estimates.dta", country_iso = "KEN", level = "national") cs <- load_csection_estimates("csection_national.dta", country_iso = "KEN", level = "national") plot_data <- prepare_private_sector_plot_data(dt, cs) ## End(Not run)
cd_data classPrints a summary of an object of class cd_data,
including data dimensions, available years,
regions, variable groups, and any quality metrics associated with the data.
It uses the cli package for enhanced, styled output.
## S3 method for class 'cd_data' print(x, ...)## S3 method for class 'cd_data' print(x, ...)
x |
An object of class |
... |
Additional arguments (currently not used). |
This print method provides the following summary sections:
Data Summary: Shows the number of observations and variables in merged_data.
Years Available: Lists unique years present in merged_data.
Regions Available: Lists unique regions in the adminlevel_1 column.
Variable Groups: Displays predefined groups of variables, including ANC, delivery, vaccination, PNC, OPD, and IPD groups.
Quality Metrics: If present, prints quality_metrics for additional data insights.
Invisibly returns x. This function is called for its side effect of printing
a formatted summary of the cd_data object.
ancvargroup: Variables related to antenatal care.
idelvvargroup: Variables related to delivery.
vaccvargroup: Variables related to vaccinations.
pncvargroup: Variables related to postnatal care.
opdvargroup: Variables related to outpatient care.
ipdvargroup: Variables related to inpatient care.
## Not run: # Assuming `cd_data_obj` is an object of class `cd_data`: print(cd_data_obj) ## End(Not run)## Not run: # Assuming `cd_data_obj` is an object of class `cd_data`: print(cd_data_obj) ## End(Not run)
Sets up, inside a module server, an observer that puts a file upload zone back in its
"uploaded" state each time the zone appears on the page, when the dataset holds something the
user uploaded for the zone's field (cache()$is_default(field) is FALSE). The zone shows
the name of the file uploaded in this session, or a general "file on record" label when the
name is not known (for example after loading a saved dataset).
push_upload_on_remount( input, session, i18n, input_id, field, cache, filename_val )push_upload_on_remount( input, session, i18n, input_id, field, cache, filename_val )
input, session
|
The |
i18n |
The app's translator (a |
input_id |
The input id of the upload zone, without the namespace, a string. |
field |
The name of the dataset field the zone fills, a string (for example
|
cache |
A reactive that returns the dataset, a CacheConnection. |
filename_val |
A reactive value ( |
Nothing useful. The function is called for its side effect of registering the observer.
## Not run: # in a module's ui: the upload zone cd_file_upload(ns("un_data"), label = "title_upload_un_estimates", accept = ".dta", i18n = i18n) # in its server: remember the uploaded file's name, and show it when the zone comes back un_filename <- reactiveVal(NULL) observeEvent(input$un_data, un_filename(input$un_data$name)) observeEvent(input$un_data_reset, un_filename(NULL)) push_upload_on_remount(input, session, i18n, "un_data", "un_estimates", cache, un_filename) ## End(Not run)## Not run: # in a module's ui: the upload zone cd_file_upload(ns("un_data"), label = "title_upload_un_estimates", accept = ".dta", i18n = i18n) # in its server: remember the uploaded file's name, and show it when the zone comes back un_filename <- reactiveVal(NULL) observeEvent(input$un_data, un_filename(input$un_data$name)) observeEvent(input$un_data_reset, un_filename(NULL)) push_upload_on_remount(input, session, i18n, "un_data", "un_estimates", cache, un_filename) ## End(Not run)
Turns the results of run_all_quality_checks() into two tables: a summary with one row per
check, and a list with one row per issue found.
quality_issues_table(results, labels = NULL)quality_issues_table(results, labels = NULL)
results |
A named list. What |
labels |
An optional named character vector that maps a check's key ( |
A list of two tibbles. summary has columns check, severity, status
("passed" or "issue") and issues (the number of issues). issues has columns check,
severity and issue, with one row for each thing a check found (each district-year,
each name, each message) and nothing shortened.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) results <- run_all_quality_checks(cache) tables <- quality_issues_table(results) tables$summary tables$issues # A check under a name of your own quality_issues_table(results, labels = c(indicator_emptiness = "Indicators without data"))$summarypath <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) results <- run_all_quality_checks(cache) tables <- quality_issues_table(results) tables$summary tables$issues # A check under a name of your own quality_issues_table(results, labels = c(indicator_emptiness = "Indicators without data"))$summary
Reads a shapefile from the files of an uploaded folder, as a Shiny multi-file or folder
fileInput() gives them: a data frame with each file's original name and the datapath it
was saved to. The .shp, .dbf, .shx and .prj files are all required; they are copied
under their original names into one temporary directory and read from there. Other files are
ignored.
read_shapefile_folder(files_df, call = caller_env())read_shapefile_folder(files_df, call = caller_env())
files_df |
A data frame with |
call |
The calling environment, forwarded to |
The uploaded shapefile as a valid sf object, reprojected to EPSG:4326. Column names are
exactly as uploaded: the column holding the unit names is not renamed to NAME_1.
## Not run: # in a Shiny server, for fileInput("shapefile", "Shapefile", multiple = TRUE) in the page boundaries <- read_shapefile_folder(input$shapefile) # outside Shiny: the parts of a shapefile kept in one folder parts <- list.files("boundaries", full.names = TRUE) boundaries <- read_shapefile_folder(data.frame(name = basename(parts), datapath = parts)) names(boundaries) ## End(Not run)## Not run: # in a Shiny server, for fileInput("shapefile", "Shapefile", multiple = TRUE) in the page boundaries <- read_shapefile_folder(input$shapefile) # outside Shiny: the parts of a shapefile kept in one folder parts <- list.files("boundaries", full.names = TRUE) boundaries <- read_shapefile_folder(data.frame(name = basename(parts), datapath = parts)) names(boundaries) ## End(Not run)
Optional upload zones for the reference estimates the analysis uses: UN
estimates, WUENIC estimates and UN mortality estimates, each a Stata file (.dta). Which
zones show is set by the app (cd_wizard_config()$reference_uploads). The dataset uses
built-in estimates for its country until the user uploads a file. An uploaded file is read
for the dataset's country and saved with cache()$set_un_estimates(),
cache()$set_wuenic_estimates() or cache()$set_un_mortality_estimates(). A zone's reset
button goes back to the built-in estimates (cache()$clear_un_estimates() and so on). A file
that cannot be read shows an error banner under its zone. These uploads do not affect whether
the Upload Data step counts as complete.
reference_estimates_ui(id, i18n) reference_estimates_server(id, cache, i18n)reference_estimates_ui(id, i18n) reference_estimates_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
The UI has no card of its own: it is a divided section meant to sit in the same card as
upload_box_ui(). UN estimates are read for the years of the dataset
(cache()$data_years), so that zone does nothing until the dataset has years.
reference_estimates_ui() returns the UI as Shiny tags: a divider and a group of
upload zones. reference_estimates_server() is called for its side effects and returns
nothing useful.
## Not run: # in the server of the Load Data screen: the Upload Data step's page is one card # holding the dataset's upload zone and these reference-data zones panel <- list(key = "upload", ui = cd_card( title = i18n$t("title_upload_dataset_card"), width = 12, upload_box_ui(ns("upload_box"), i18n), reference_estimates_ui(ns("reference_estimates"), i18n) )) reference_estimates_server("reference_estimates", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen: the Upload Data step's page is one card # holding the dataset's upload zone and these reference-data zones panel <- list(key = "upload", ui = cd_card( title = i18n$t("title_upload_dataset_card"), width = 12, upload_box_ui(ns("upload_box"), i18n), reference_estimates_ui(ns("reference_estimates"), i18n) )) reference_estimates_server("reference_estimates", cache, i18n) ## End(Not run)
Adds or modifies a group definition by name. If the name already exists,
use on_conflict = "replace" to replace the entire definition, or
on_conflict = "merge" to union indicators per category.
register_indicator_group( name, value, on_conflict = c("replace", "merge", "error") )register_indicator_group( name, value, on_conflict = c("replace", "merge", "error") )
name |
A non-empty string: the group/profile name to create or modify. |
value |
A named list: each element is a category containing a character vector of indicator codes. |
on_conflict |
One of |
Reserved names "auto" and "custom" cannot be registered.
If name matches a built-in (e.g. "rmncah"), the override will be layered
on top of the built-in according to on_conflict.
The merged, live view is available via .get_all_groups() or
get_indicator_groups().
Invisibly returns name.
# Replace RMNCAH completely register_indicator_group( "rmncah", list(anc = c("anc1","anc4"), idelv = c("sba")), on_conflict = "replace" ) # Extend RMNCAH by merging into existing categories (union) register_indicator_group( "rmncah", list(hiv = c("hiv_test","pmtct1")), on_conflict = "merge" ) # Back to the built-in group reset_indicator_group("rmncah")# Replace RMNCAH completely register_indicator_group( "rmncah", list(anc = c("anc1","anc4"), idelv = c("sba")), on_conflict = "replace" ) # Extend RMNCAH by merging into existing categories (union) register_indicator_group( "rmncah", list(hiv = c("hiv_test","pmtct1")), on_conflict = "merge" ) # Back to the built-in group reset_indicator_group("rmncah")
What each kind draws and which settings it takes. The builder offers these; render_report_block() draws them.
report_block_kinds(group = get_selected_group())report_block_kinds(group = get_selected_group())
group |
The indicator group; kinds that only make sense for one group ( |
The kinds are listed in the order of the analysis (their group: data quality, adjustment, denominators, national,
sub-national, region, mortality, service utilization, health system). The standard report files add their own kinds
(see the top of the standard reports section).
A named list; each entry has type ("chart" or "table"), group, label, indicators ("analysis",
a character vector, or NULL when the kind has no indicator), levels, variants (named character vector or
NULL), year (whether a year is chosen), regional (whether it is drawn for one region) and groups (the
indicator groups it is for).
kinds <- report_block_kinds("rmncah") head(names(kinds)) str(kinds$reporting_rate) # the kinds the vaccine group does not have setdiff(names(kinds), names(report_block_kinds("vaccine")))kinds <- report_block_kinds("rmncah") head(names(kinds)) str(kinds$reporting_rate) # the kinds the vaccine group does not have setdiff(names(kinds), names(report_block_kinds("vaccine")))
One per analysis section (data quality, adjustment, denominators, national coverage, inequality, mortality,
service utilization, health system, private sector), then the synthesis chartbook and the sub-national one-pager: the
Countdown report templates rebuilt as blocks, which the builder opens as editable copies. The one-pager is about one
region: its blocks use the report's region (region = "@report"). It is a slide deck of one dense slide.
report_presets(lang = "en", group = get_selected_group())report_presets(lang = "en", group = get_selected_group())
lang |
The language of the report's text: |
group |
The indicator group ( |
A named list of reports in the order of the analysis, each list(name, description, kind, design, cover, blocks) for a document (kind = "document"), or list(name, description, kind = "deck", design, cover, slides)
for a slide deck (see export_deck()). report_project_blocks() gives the blocks of either.
presets <- report_presets(lang = "en", group = "rmncah") names(presets) presets$mortality$name length(presets$mortality$blocks) # the vaccine group's reports, named in French vapply(report_presets("fr", group = "vaccine"), function(p) p$name, character(1))presets <- report_presets(lang = "en", group = "rmncah") names(presets) presets$mortality$name length(presets$mortality$blocks) # the vaccine group's reports, named in French vapply(report_presets("fr", group = "vaccine"), function(p) p$name, character(1))
The data quality page on how completely facilities report. Its first card shows the reporting rate
of the chosen indicator for each admin level 1 area or district, as a heat map or as a bar chart
(two tabs). Below it are a chart of the district reporting rates, for the country or for the
chosen region, and a table of the areas whose rate is below the performance threshold in the
year picked on the table. The filters are the indicator (the app's reporting_rate_indicators
setting), the performance threshold and the admin level with its region.
reporting_rate_ui(id, i18n) reporting_rate_server(id, cache, i18n, active = reactive(TRUE))reporting_rate_ui(id, i18n) reporting_rate_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
The page reads reporting_rate_admin1, reporting_rate_district and district_reporting_rate
from the dataset, and calls its calculate_reporting_rate() and
calculate_district_reporting_rate() when a region is chosen. The performance threshold comes
from the dataset's performance_threshold, and a change to it is saved there with
set_performance_threshold().
reporting_rate_ui() returns the page's UI as Shiny tags. reporting_rate_server() is
called for its side effects.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "reporting_rate", ui = reporting_rate_ui, server = reporting_rate_server, title = "title_rr_main", section = "lbl_nav_section_quality", subtitle = "sub_rr_main" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "reporting_rate", ui = reporting_rate_ui, server = reporting_rate_server, title = "title_rr_main", section = "lbl_nav_section_quality", subtitle = "sub_rr_main" ) ## End(Not run)
Removes a user override for name. If name matches a built-in group, the
built-in remains intact; only the override layer is removed.
reset_indicator_group(name)reset_indicator_group(name)
name |
Group name whose override should be removed. |
Invisibly returns name.
reset_indicator_group("rmncah")reset_indicator_group("rmncah")
Looks up the country named in the Admin sheet and returns its name and ISO3 code. Unlike
the lookup in new_countdown(), it does not stop with an error when the country cannot be
resolved. Use it to show the country before the sheets are merged.
resolve_country_best_effort(admin_data)resolve_country_best_effort(admin_data)
admin_data |
A data frame. The cleaned Admin sheet, before the sheets are merged. |
The country is resolved only when the country column holds exactly one distinct value,
ignoring missing values, and that value is close to a name in the package's list of
countries. This function does not validate the sheet. Use check_single_country() and
check_country_recognized() for that.
A list with two elements: country (the country's name as the package spells it)
and country_iso (its ISO3 code), both strings. Both are NULL if the sheet has no
country column or the country cannot be resolved.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] resolve_country_best_effort(admin) # Nothing is returned, and no error raised, for a country that is not recognized admin$country <- "Atlantis" resolve_country_best_effort(admin)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") sheets <- load_excel_parts(path) admin <- sheets$parts[[sheets$admin_sheet_name]] resolve_country_best_effort(admin) # Nothing is returned, and no error raised, for a country that is not recognized admin$country <- "Atlantis" resolve_country_best_effort(admin)
Sets up, inside a module server, a link button that shows only while a field of the dataset
holds something the user set (cache()$is_default(field) is FALSE), and that calls
clear_fn() when pressed. The two mapping steps use it for their "clear mapping" link. The
module's UI needs uiOutput(ns(output_id)) where the link goes.
restore_default_control( ns, output, input, output_id, field, cache, clear_fn, label_key, i18n )restore_default_control( ns, output, input, output_id, field, cache, clear_fn, label_key, i18n )
ns |
The namespace function of the calling module ( |
output, input
|
The |
output_id |
The id of the output that shows the link, a string. The button's own input id is the same. |
field |
The name of the dataset field to watch, a string (for example
|
cache |
A reactive that returns the dataset, a CacheConnection. |
clear_fn |
A function without arguments that clears the field, for example
|
label_key |
The translation key of the link's text, a string. |
i18n |
The app's translator (a |
Nothing useful. The function is called for its side effects: it sets
output[[output_id]] and registers an observer.
## Not run: # in a module's ui: where the link goes uiOutput(ns("survey_map_restore")) # in its server: a "clear mapping" link that shows while a survey mapping is saved restore_default_control( session$ns, output, input, "survey_map_restore", "survey_mapping", cache, clear_fn = function() cache()$clear_survey_mapping(), label_key = "btn_upload_clear_mapping", i18n = i18n ) ## End(Not run)## Not run: # in a module's ui: where the link goes uiOutput(ns("survey_map_restore")) # in its server: a "clear mapping" link that shows while a survey mapping is saved restore_default_control( session$ns, output, input, "survey_map_restore", "survey_mapping", cache, clear_fn = function() cache()$clear_survey_mapping(), label_key = "btn_upload_clear_mapping", i18n = i18n ) ## End(Not run)
robust_max calculates the maximum value of a numeric vector while handling
missing values. If all values in the vector are NA, the function returns NA
instead of raising an error.
robust_max(x, fallback = NA)robust_max(x, fallback = NA)
x |
A numeric vector. |
fallback |
argument allows you to specify a value to return when all elements are NA |
The maximum value of x, or NA if all values are NA.
# Example usage robust_max(c(1, 2, 3, NA)) # Returns 3 robust_max(c(NA, NA)) # Returns NA robust_max(c(-Inf, 0, 10)) # Returns 10# Example usage robust_max(c(1, 2, 3, NA)) # Returns 3 robust_max(c(NA, NA)) # Returns NA robust_max(c(-Inf, 0, 10)) # Returns 10
The keys of the tabs of the first card on the reporting rate page (reporting_rate_ui()): the heat
map and the bar chart.
rr_indicatorsrr_indicators
A character vector.
rr_indicatorsrr_indicators
Runs the data quality checks on the data held in a cache and returns the result of each one, whether it passed or not. It does not stop on a problem, so a caller can show the whole report.
run_all_quality_checks(cache)run_all_quality_checks(cache)
cache |
A |
Which checks run depends on what the cache holds:
If it holds unmerged sheets (cache$wizard_parts), the checks run on the separate sheets,
so a problem can be traced to the sheet it comes from.
Otherwise, if it holds results saved when the sheets were merged
(cache$wizard_quality_results), those saved results are returned and no check is run.
Otherwise the checks run on the merged dataset (cache$countdown_data). This set has
fewer checks than the one for unmerged sheets.
A named list with one element per check. Each element is a list with:
ok: TRUE if the check passed.
severity: "blocking" (the caller should not go on until the problem is fixed),
"informational" (shown, but does not block) or "mapping" (an admin level 1 name with
no match in the survey or the shapefile; shown, but does not block).
detail: what the check returned, which is NULL, a character vector or a tibble,
depending on the check.
quality_issues_table() and write_quality_issues() to tabulate or save the result.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") # On a loaded dataset cache <- load_cache_data(path) results <- run_all_quality_checks(cache) names(results) results$indicator_emptiness # On the sheets of a workbook, before they are merged sheets <- load_excel_parts(path) results <- run_all_quality_checks(init_CacheConnection(wizard_parts = sheets)) Filter(function(result) !result$ok, results)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") # On a loaded dataset cache <- load_cache_data(path) results <- run_all_quality_checks(cache) names(results) results$indicator_emptiness # On the sheets of a workbook, before they are merged sheets <- load_excel_parts(path) results <- run_all_quality_checks(init_CacheConnection(wizard_parts = sheets)) Filter(function(result) !result$ok, results)
save_data saves processed Countdown 2030 data to either an RDS or DTA file.
It checks that the input data is of class cd_data before saving.
save_data(.data, file = "master_dataset.dta")save_data(.data, file = "master_dataset.dta")
.data |
A tibble of class |
file |
A string. The path to the file where the data should be saved, with
extension |
The function verifies that the data argument is of class cd_data. It then
saves the data in the specified file format based on the file extension.
No return value. This function is called for its side effects (saving the data to an RDS or DTA file).
## Not run: # Save processed Countdown 2030 data to an RDS file save_data(cd_data, "processed_cd2030_data.rds") # Save processed Countdown 2030 data to a DTA file save_data(cd_data, "processed_cd2030_data.dta") ## End(Not run)## Not run: # Save processed Countdown 2030 data to an RDS file save_data(cd_data, "processed_cd2030_data.rds") # Save processed Countdown 2030 data to a DTA file save_data(cd_data, "processed_cd2030_data.dta") ## End(Not run)
Writes the admin, population, completeness and service data downloaded from DHIS2 to one Excel
workbook, with styled sheets for each type of data. A file that already exists at filename
is overwritten.
save_dhis2_excel(.data, filename, last_org)save_dhis2_excel(.data, filename, last_org)
.data |
A list containing the structured DHIS2 data, including |
filename |
A string specifying the file path and name where the Excel workbook will be saved. |
last_org |
Character. Name of the lowest organisation-unit column (for
example |
The workbook contains sheets for the different types of DHIS2 data:
Admin Data: Maps health districts to administrative units.
Population Data: Contains official population data for denominators in health reporting.
Completeness Data: Tracks reporting completeness metrics.
Service Data: Records service delivery numbers.
Each sheet is styled, with column headers, instructions, and frozen panes. Instructions are added to guide users on how to input or interpret data.
Saves the workbook to the specified filename.
## Not run: save_dhis2_excel(data, "dhis2_data.xlsx") ## End(Not run)## Not run: save_dhis2_excel(data, "dhis2_data.xlsx") ## End(Not run)
Combines the service, completeness, population and admin data downloaded from DHIS2 into one Countdown dataset, with a row per district, year and month and a column per data element.
save_dhis2_master_data(.data)save_dhis2_master_data(.data)
.data |
A list containing the structured DHIS2 data, including |
Pivots the service, completeness and population data to a wide format and merges them on
their common keys (district, year and, where present, month), then adds the admin data
by district. The merged data is standardized and made into a cd_data object, which checks
that the required columns are present.
A tibble of class cd_data holding the combined and standardized DHIS2 dataset.
## Not run: master_dataset <- save_dhis2_master_data(data) ## End(Not run)## Not run: master_dataset <- save_dhis2_master_data(data) ## End(Not run)
Keeps year and the two columns for a single indicator's raw and adjusted
values, e.g. anc1_raw and anc1_adj.
select_adjustment_value(.data, indicator)select_adjustment_value(.data, indicator)
.data |
A tibble of class |
indicator |
A single indicator name. Must be one of |
A tibble with class cd_adjustment_values_filtered containing:
year
<indicator>_raw
<indicator>_adj
The result carries an attribute indicator with the selected indicator.
## Not run: x <- select_adjustment_value(adj_values, "anc1") attr(x, "indicator") # "anc1" ## End(Not run)## Not run: x <- select_adjustment_value(adj_values, "anc1") attr(x, "indicator") # "anc1" ## End(Not run)
select_coverage extracts specific coverage indicators and denominators from a
combined coverage dataset, applies regional filtering, and reshapes the data
for analysis and visualisation.
select_coverage( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), region = NULL )select_coverage( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), region = NULL )
.data |
A |
indicator |
Coverage indicators to include (e.g., |
denominator |
Denominator sources for coverage calculations (e.g., |
region |
Name of the subnational unit (at the data's |
A reshaped data frame with filtered indicators and denominators.
## Not run: select_coverage(combined_data, c("penta3", "measles1"), "dhis2", "Central Province") ## End(Not run)## Not run: select_coverage(combined_data, c("penta3", "measles1"), "dhis2", "Central Province") ## End(Not run)
select_inequality refines the output of calculate_inequality by selecting
specific indicators and denominators for analysis. It extracts and renames relevant
columns to streamline further analyses.
select_inequality( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived") )select_inequality( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived") )
.data |
A |
indicator |
A character vector of health indicators to include (e.g., |
denominator |
A character vector of denominators to filter by (e.g., |
A tibble containing filtered subnational inequality metrics for the specified indicators and denominators.
## Not run: # Filter for Penta-3 coverage using DHIS-2 denominator filtered_data <- inequality_metrics %>% select_inequality(indicator = "penta3", denominator = "dhis2") ## End(Not run)## Not run: # Filter for Penta-3 coverage using DHIS-2 denominator filtered_data <- inequality_metrics %>% select_inequality(indicator = "penta3", denominator = "dhis2") ## End(Not run)
Extracts and filters indicator coverage data by year, denominator type, and color palette for visualization.
select_mapping_data( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), palette = c("Reds", "Blues", "Greens", "Purples", "YlGnBu"), plot_year = NULL )select_mapping_data( .data, indicator, denominator = c("dhis2", "anc1", "penta1", "penta1derived", "anc1derived"), palette = c("Reds", "Blues", "Greens", "Purples", "YlGnBu"), plot_year = NULL )
.data |
A |
indicator |
Character. Indicator name (e.g., |
denominator |
Character. One of: |
palette |
Character. Color palette for mapping.
One of: |
plot_year |
Optional integer or vector of years to filter. |
A tibble of class "cd_mapping_filtered".
## Not run: filtered <- select_mapping_data( data, indicator = "anc4", denominator = "anc1", palette = "Blues", plot_year = 2021 ) ## End(Not run)## Not run: filtered <- select_mapping_data( data, indicator = "anc4", denominator = "anc1", palette = "Blues", plot_year = 2021 ) ## End(Not run)
Selects one institutional mortality rate from a cd_mortality_summary object, optionally for
given years, and joins the admin level 1 boundaries of the country so the result can be mapped.
select_mortality_summary( .data, country_iso, indicator = c("mmr", "sbr", "nn"), plot_year = NULL, subnational_map = NULL, palette = c("Reds", "Blues", "Greens", "Purples", "YlGnBu") )select_mortality_summary( .data, country_iso, indicator = c("mmr", "sbr", "nn"), plot_year = NULL, subnational_map = NULL, palette = c("Reds", "Blues", "Greens", "Purples", "YlGnBu") )
.data |
A |
country_iso |
A character string. ISO3 code of the country, used to load its boundaries. |
indicator |
Character. Mortality indicator to select: |
plot_year |
Optional integer or vector of years to filter. |
subnational_map |
Optional. A data frame to join with the shapefile to add metadata. |
palette |
Character. RColorBrewer sequential palette for the map (default |
Selects the column of the mortality indicator (mmr_inst, sbr_inst or nn_inst) and keeps
only plot_year when it is given. Joins the rates to the admin level 1 boundaries by unit name,
or through subnational_map when the names in the data differ from those of the shapefile, and
renames the geometry column to geometry.
A tibble of class cd_mortality_summary_filtered, ready for geospatial plotting.
## Not run: select_mortality_summary( mortality_data, country_iso = "NGA", indicator = "sbr", plot_year = 2021:2023 ) ## End(Not run)## Not run: select_mortality_summary( mortality_data, country_iso = "NGA", indicator = "sbr", plot_year = 2021:2023 ) ## End(Not run)
Prepares a cd_service_utilization object for non-spatial plotting (e.g., time series)
by filtering by administrative region and indicator type.
select_service_utilization( .data, indicator = c("opd", "ipd", "under5", "cfr", "deaths"), region = NULL )select_service_utilization( .data, indicator = c("opd", "ipd", "under5", "cfr", "deaths"), region = NULL )
.data |
A |
indicator |
Character. The indicator to visualize. Options include |
region |
A single unit name to filter by. Required when data is subnational
( |
Checks the class of .data and the indicator value. Subnational data is filtered to the unit
named by region; for national data region must not be given. The result keeps every column of
.data and is tagged with the cd_service_utilization_filtered class for plotting.
A tibble of class cd_service_utilization_filtered, with an attached indicator attribute for plotting.
## Not run: # Filter IPD indicator for Central region filtered <- select_service_utilization(service_data, indicator = "ipd", region = "Central") ## End(Not run)## Not run: # Filter IPD indicator for Central region filtered <- select_service_utilization(service_data, indicator = "ipd", region = "Central") ## End(Not run)
Persists the selected group in session state and as an option
(options(cd2030.selected_group = <name>)). Downstream helpers can retrieve
it with get_selected_group().
set_selected_group(group)set_selected_group(group)
group |
Group name. Must exist in |
Invisibly returns the resolved group name.
set_selected_group("rmncah") get_selected_group()set_selected_group("rmncah") get_selected_group()
An optional step where the user can replace the built-in map of the country with their own
shapefile. The user uploads the shapefile's folder (its .shp, .dbf, .shx and .prj
files), picks the column that holds the admin level 1 names (NAME_1 is preselected when the
file has it), and confirms. Confirming saves the shapefile with cache()$set_shapefile() and
the column with cache()$set_shapefile_name_field(); nothing is saved before that. The
zone's reset button goes back to the built-in shapefile (cache()$clear_shapefile()). The
step never blocks the wizard while the built-in shapefile is in use (see
step_shapefile_complete()).
shapefile_step_ui(id, i18n) shapefile_step_server(id, cache, i18n)shapefile_step_ui(id, i18n) shapefile_step_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
Under the upload zone the step shows: an error banner when the folder cannot be read; a
banner that says whether the built-in or a custom shapefile is in use; and a warning with the
number of admin level 1 names of the dataset that do not match the shapefile
(cache()$check_shapefile_admin_names()), which the Map Shapefile Names step resolves.
shapefile_step_ui() returns the UI as Shiny tags: a card with the upload zone.
shapefile_step_server() is called for its side effects and returns nothing useful.
## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "shapefile", ui = shapefile_step_ui(ns("shapefile_step"), i18n)) shapefile_step_server("shapefile_step", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "shapefile", ui = shapefile_step_ui(ns("shapefile_step"), i18n)) shapefile_step_server("shapefile_step", cache, i18n) ## End(Not run)
What makes a fitted model large (samples, stan_model) and no chart or table reads: see
generate_bayes_model()'s keep_samples. A model that has neither is returned as it is.
slim_bayes_model(model)slim_bayes_model(model)
model |
A fitted model. |
The model without them, its class and attributes kept.
# a stand-in for a model fitted with keep_samples = TRUE model <- structure( list(posteriors = list(), samples = matrix(0, 1000, 50), stan_model = "the compiled model"), class = c("cd_bayes_model", "list"), indicator = "penta3" ) slim <- slim_bayes_model(model) names(slim) attr(slim, "indicator") object.size(slim) < object.size(model)# a stand-in for a model fitted with keep_samples = TRUE model <- structure( list(posteriors = list(), samples = matrix(0, 1000, 50), stan_model = "the compiled model"), class = c("cd_bayes_model", "list"), indicator = "penta3" ) slim <- slim_bayes_model(model) names(slim) attr(slim, "indicator") object.size(slim) < object.size(model)
Each function looks at a dataset and says whether one step of the Load Data wizard is done.
The wizard uses them, through wizard_step_defs and compute_step_states(), to decide which
steps are open and when Continue is enabled. step_shapefile_touched() is not a completion
test: it says whether the user has done anything on the Shapefile step, which decides whether
that step's button reads "Skip" or "Continue".
step_upload_complete(cd) step_quality_complete(cd) step_national_rates_complete(cd) step_survey_files_complete(cd) step_shapefile_complete(cd) step_shapefile_touched(cd) step_survey_mapping_complete(cd) step_map_mapping_complete(cd)step_upload_complete(cd) step_quality_complete(cd) step_national_rates_complete(cd) step_survey_files_complete(cd) step_shapefile_complete(cd) step_shapefile_touched(cd) step_survey_mapping_complete(cd) step_map_mapping_complete(cd)
cd |
The dataset, a CacheConnection object (the value of |
The survey files, the reference estimates and the shapefile have built-in data for the
dataset's country, so reading them from the dataset never gives NULL. The tests for those
steps therefore use cd$is_default(), which says whether the user has uploaded something.
The two name mappings have no built-in data, so their tests check for NULL: a mapping
exists only after the user has saved the matching dialog at least once.
TRUE or FALSE. Every function returns FALSE for a NULL dataset, except
step_shapefile_complete(), which returns TRUE. Otherwise each returns TRUE when:
step_upload_complete(): the dataset holds unmerged sheets (cd$wizard_parts) or merged
data with at least one row (cd$countdown_data).
step_quality_complete(): the upload is complete and every check of severity
"blocking" in run_all_quality_checks() has passed.
step_national_rates_complete(): every national rate named by
national_rates_required_fields() and every survey estimate named by
survey_estimates_required_fields() has a value, and cd$survey_year is set.
step_survey_files_complete(): the user has uploaded all five survey files
(survey_fields).
step_shapefile_complete(): the built-in shapefile is in use, or the user has uploaded
one and cd$shapefile_name_field is set.
step_shapefile_touched(): the user has uploaded a shapefile.
step_survey_mapping_complete(): a survey name mapping is saved (cd$survey_mapping).
step_map_mapping_complete(): a shapefile name mapping is saved (cd$map_mapping).
old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) step_upload_complete(cache) step_quality_complete(cache) step_national_rates_complete(cache) step_survey_files_complete(cache) step_shapefile_complete(cache) step_shapefile_touched(cache) step_survey_mapping_complete(cache) step_map_mapping_complete(cache) # no dataset loaded step_upload_complete(NULL) options(old)old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) step_upload_complete(cache) step_quality_complete(cache) step_national_rates_complete(cache) step_survey_files_complete(cache) step_shapefile_complete(cache) step_shapefile_touched(cache) step_survey_mapping_complete(cache) step_map_mapping_complete(cache) # no dataset loaded step_upload_complete(NULL) options(old)
Shows coverage by year for one region or one district: the estimate from the health facility
data, with the denominator selected for the indicator, beside the survey and WUENIC estimates.
Two filters choose the admin level (admin level 1 or district) and then the area at that level;
the charts wait until an area is chosen. The page is the coverage charts (coverage_ui()) for
that area: one card with a tab for each indicator in cd_cfg("nat_cov_indicators") and a Custom
tab. The data come from the dataset's get_filtered_coverage(), which reads
cache()$calculate_coverage() for the chosen level.
subnational_coverage_ui(id, i18n) subnational_coverage_server(id, cache, i18n, active = reactive(TRUE))subnational_coverage_ui(id, i18n) subnational_coverage_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
subnational_coverage_ui() returns the page's UI as Shiny tags.
subnational_coverage_server() returns what coverage_server() returns: a reactive that holds
the key of the tab shown.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_coverage", ui = subnational_coverage_ui, server = subnational_coverage_server, title = "title_nav_subnational_coverage", section = "title_nav_subnational_analysis", subtitle = "sub_cov_subnational" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_coverage", ui = subnational_coverage_ui, server = subnational_coverage_server, title = "title_nav_subnational_coverage", section = "title_nav_subnational_analysis", subtitle = "sub_cov_subnational" ) ## End(Not run)
A card of the Denominator selection page (denominator_selection_ui()) with one tab per
indicator (the app's sub_derived_indicators setting). Each tab has a chart of the indicator's
coverage in each admin level 1 area, for each denominator the app offers. The card has no
filters. It calls the dataset's calculate_derived_coverage() for admin level 1 and reads its
survey_year, which the chart's title names.
subnational_denominator_ui(id, i18n) subnational_denominator_server(id, cache, i18n, active = reactive(TRUE))subnational_denominator_ui(id, i18n) subnational_denominator_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
subnational_denominator_ui() returns the card's UI as Shiny tags.
subnational_denominator_server() is called for its side effects.
Shows how coverage differs between districts. A filter chooses the admin level. With admin level
1, a second filter chooses a region, and the charts show the coverage of that region's districts;
they wait until a region is chosen. With district, there is no second filter and the charts show
every district of the country. The page is the inequality charts (inequality_ui()), which read
cache()$inequality_district through the dataset's get_filtered_inequality(); that table
measures each district against the national value.
subnational_inequality_ui(id, i18n) subnational_inequality_server(id, cache, i18n, active = reactive(TRUE))subnational_inequality_ui(id, i18n) subnational_inequality_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
subnational_inequality_ui() returns the page's UI as Shiny tags.
subnational_inequality_server() returns what inequality_server() returns: a reactive that
holds the key of the tab shown.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_inequality", ui = subnational_inequality_ui, server = subnational_inequality_server, title = "title_inequ_subnational", section = "title_nav_subnational_analysis", subtitle = "sub_inequ_subnational" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_inequality", ui = subnational_inequality_ui, server = subnational_inequality_server, title = "title_inequ_subnational", section = "title_nav_subnational_analysis", subtitle = "sub_inequ_subnational" ) ## End(Not run)
The maps of the national inequality page: one card with a tab for each of the app's default
indicators (cd_default_indicator_set()) and a Custom tab for any other analysis indicator. A
tab draws maps of the indicator's coverage in each admin level 1 area, with the denominator
selected for the indicator, for the years chosen for mapping (cache()$mapping_years). It reads
the dataset's get_filtered_mapping_data(), which joins the admin level 1 coverage to the map
through the dataset's map mapping. The piece has no filters of its own: the page gives it the
colour palette and the tab to show.
subnational_mapping_ui(id, i18n) subnational_mapping_server( id, cache, i18n, palette, selected_tab, active = reactive(TRUE) )subnational_mapping_ui(id, i18n) subnational_mapping_server( id, cache, i18n, palette, selected_tab, active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
palette |
A reactive that returns the name of the maps' colour palette (for example
|
selected_tab |
A reactive that returns the key of the tab to show, or |
active |
A reactive that is |
subnational_mapping_ui() returns the card's UI as Shiny tags.
subnational_mapping_server() returns a reactive that holds the key of the tab shown: an
indicator's name, or "custom".
## Not run: # the maps below the inequality charts, showing the tab the charts show my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, inequality_ui(ns("inequality"), i18n), cd_map_options(cd_palette_chip(ns("palette"), i18n)), subnational_mapping_ui(ns("map"), i18n) ) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { selected_tab <- inequality_server("inequality", cache, i18n, reactive("adminlevel_1"), active = active) subnational_mapping_server("map", cache, i18n, reactive(input$palette), selected_tab, active = active) }) } ## End(Not run)## Not run: # the maps below the inequality charts, showing the tab the charts show my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, inequality_ui(ns("inequality"), i18n), cd_map_options(cd_palette_chip(ns("palette"), i18n)), subnational_mapping_ui(ns("map"), i18n) ) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { selected_tab <- inequality_server("inequality", cache, i18n, reactive("adminlevel_1"), active = active) subnational_mapping_server("map", cache, i18n, reactive(input$palette), selected_tab, active = active) }) } ## End(Not run)
Shows how much of one region meets the coverage targets. One filter chooses an admin level 1
region; the page waits until one is chosen, and the unit counted is always the district. The page
is the target charts and table (target_ui()) for that region: by year, the percentage of the
region's districts that meet each target group's target (the dataset's
get_filtered_threshold()), and a table of the areas of the region whose coverage of a chosen
indicator reaches the target (the dataset's get_high_performers()).
subnational_target_ui(id, i18n) subnational_target_server(id, cache, i18n, active = reactive(TRUE))subnational_target_ui(id, i18n) subnational_target_server(id, cache, i18n, active = reactive(TRUE))
id |
The module's id. A page's id is also its entry in the app's page registry. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
active |
A reactive that is |
subnational_target_ui() returns the page's UI as Shiny tags.
subnational_target_server() returns what target_server() returns: a reactive that holds the
key of the tab shown.
## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_target", ui = subnational_target_ui, server = subnational_target_server, title = "title_nav_global_coverage", section = "title_nav_subnational_analysis", subtitle = "sub_target_subnational" ) ## End(Not run)## Not run: # the page's entry in an app's page registry cd_page_def( id = "subnational_target", ui = subnational_target_ui, server = subnational_target_server, title = "title_nav_global_coverage", section = "title_nav_subnational_analysis", subtitle = "sub_target_subnational" ) ## End(Not run)
Computes and summarizes adjusted mortality ratio estimates based on completeness correction factors for different completeness-to-incompleteness ratios (CI ratios).
summarise_completeness_ratio( .data, plot_type = c("mmr", "sbr", "nn"), lbr_mean = 0 )summarise_completeness_ratio( .data, plot_type = c("mmr", "sbr", "nn"), lbr_mean = 0 )
.data |
A data frame of class |
plot_type |
Character. The type of mortality ratio to summarize. Must be one of:
|
lbr_mean |
Numeric. Mean live birth registration completeness, used for
scaling completeness ratios. Default is |
A tibble of class cd_mortality_ratio_summarised with columns:
ciratio: The completeness-to-incompleteness ratio used.
name: Label for the UN estimate type (lower bound, best estimate, upper bound).
rat: The adjusted mortality ratio value.
## Not run: summarise_completeness_ratio(mortality_data, plot_type = "mmr", lbr_mean = 65) ## End(Not run)## Not run: summarise_completeness_ratio(mortality_data, plot_type = "mmr", lbr_mean = 65) ## End(Not run)
A card of the Denominator selection page (denominator_selection_ui()) with one tab per
indicator (the app's survey_comp_indicators setting). Each tab has a chart that sets the
coverage worked out from the facility data with each denominator beside the survey's estimate.
When the data has no survey coverage for the indicator, the tab shows a message with a button
that opens the Load Data screen instead of the chart. The card has no filters of its own: the
page passes it the admin level and the region. It calls the dataset's
calculate_derived_coverage(), reads its survey_year, and draws nothing until its
check_inequality_params is TRUE.
survey_comparison_ui(id, i18n) survey_comparison_server( id, cache, admin_level, region, i18n, active = reactive(TRUE) )survey_comparison_ui(id, i18n) survey_comparison_server( id, cache, admin_level, region, i18n, active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A reactive that returns the admin level the coverage is worked out for:
|
region |
A reactive that returns the name of the chosen region, or |
active |
A reactive that is |
survey_comparison_ui() returns the card's UI as Shiny tags.
survey_comparison_server() is called for its side effects.
The names of the dataset fields the Survey Files step fills, one per survey file. Each has
built-in data for the dataset's country, so cache()$is_default(field) is the way to tell
whether the user has uploaded a file for it.
survey_fieldssurvey_fields
A character vector of five field names: "national_survey", "regional_survey",
"wiq_survey" (wealth index quintiles), "area_survey" and "education_survey".
survey_fields # which survey files the user has uploaded cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) vapply(survey_fields, function(f) !cache$is_default(f), logical(1))survey_fields # which survey files the user has uploaded cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) vapply(survey_fields, function(f) !cache$is_default(f), logical(1))
An optional step where the user can upload the country's survey data in place of the built-in
survey data. It has one upload zone per file, each a Stata file (.dta): national, regional,
area, maternal education and wealth index quintile. The files can be uploaded one at a time,
and a file is recognised by the zone it is dropped into, not by its name. Each file is read
for the dataset's country and saved with cache()$set_national_survey(),
cache()$set_regional_survey(), cache()$set_area_survey(),
cache()$set_education_survey() or cache()$set_wiq_survey(). A zone's reset button goes
back to the built-in data (cache()$clear_national_survey() and so on). The step counts as
complete when all five files are uploaded (see step_survey_files_complete()); being
optional, it can be skipped.
survey_upload_ui(id, i18n) survey_upload_server(id, cache, i18n)survey_upload_ui(id, i18n) survey_upload_server(id, cache, i18n)
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
The national and regional files are read with load_survey_data(), the other three with
load_equity_data(). A file that cannot be read shows an error banner under its zone. When
the user has uploaded a regional survey whose region names do not all match the dataset's
admin level 1 names (cache()$check_survey_admin_names()), a warning under the zones gives
the number of names that do not match; the Map Survey Files step resolves them.
survey_upload_ui() returns the UI as Shiny tags: a card with the five upload zones.
survey_upload_server() is called for its side effects and returns nothing useful.
## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "survey_files", ui = survey_upload_ui(ns("survey_upload"), i18n)) survey_upload_server("survey_upload", cache, i18n) ## End(Not run)## Not run: # in the server of the Load Data screen, where `cache` is a reactive holding the dataset: # the step's page, for wizard_steps_server(), and its server panel <- list(key = "survey_files", ui = survey_upload_ui(ns("survey_upload"), i18n)) survey_upload_server("survey_upload", cache, i18n) ## End(Not run)
The body of the coverage target pages. A card of charts has a tab for each target group the app
lists (cd_cfg("target_indicators"), from "anc4", "instlivebirths", "vaccine" and
"dropout") and no Custom tab; a tab plots, by year, the percentage of regions or districts that
meet the group's target, from the dataset's get_filtered_threshold(). Below it, a table lists
the areas whose coverage of one indicator reaches the target, by year, from the dataset's
get_high_performers(); the indicator is picked above the table, and the table can be downloaded
as an Excel file. The table's title names admin level 1 or districts, following the admin level.
The piece has no page filters of its own: the page gives it the admin level and region.
target_ui(id, i18n) target_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )target_ui(id, i18n) target_server( id, cache, i18n, admin_level, region = reactive(NULL), active = reactive(TRUE) )
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection. |
admin_level |
A reactive that returns the level of the units counted: |
region |
A reactive that returns the name of an admin level 1 region, to count only its
districts, or |
active |
A reactive that is |
target_ui() returns the charts' card and the table's placeholder as Shiny tags.
target_server() returns a reactive that holds the key of the tab shown (a target group's
name).
## Not run: # the charts and table in a page whose filter chooses the admin level scope <- cd_scope("level") my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_scope_filters(ns, i18n, scope), target_ui(ns("body"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { geo <- cd_scope_server("scope", cache, i18n, scope) target_server("body", cache, i18n, geo$admin_level, geo$region, active = active) }) } ## End(Not run)## Not run: # the charts and table in a page whose filter chooses the admin level scope <- cd_scope("level") my_page_ui <- function(id, i18n) { ns <- NS(id) cd_page_ui(id, i18n, filters = cd_scope_filters(ns, i18n, scope), target_ui(ns("body"), i18n)) } my_page_server <- function(id, cache, i18n, active = reactive(TRUE)) { moduleServer(id, function(input, output, session) { geo <- cd_scope_server("scope", cache, i18n, scope) target_server("body", cache, i18n, geo$admin_level, geo$region, active = active) }) } ## End(Not run)
cd_adjustment_values ObjectsProvides a custom summary for objects of class cd_adjustment_values, typically
displaying unadjusted and adjusted values in a structured format.
## S3 method for class 'cd_adjustment_values' tbl_sum(x, ...)## S3 method for class 'cd_adjustment_values' tbl_sum(x, ...)
x |
An object of class |
... |
Additional arguments passed to or from other methods. |
This function overrides the default tbl_sum method for objects of
class cd_adjustment_values. It returns a named character vector summarizing
the table as "Unadjusted and adjusted values" along with any additional details
provided by the NextMethod() function.
A character vector with a custom table summary for cd_adjustment_values
objects.
generate_adjustment_values() for generating the cd_adjustment_values
object.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() # the summary is the header printed above the table cache$adjustment_valuescache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$adjust_data() # the summary is the header printed above the table cache$adjustment_values
Provides a custom summary for the cd_average_reporting_rate object, indicating
that the data represents annual average reporting rates across all indicators.
This summary is useful for quickly verifying the consistency of indicator reporting rates.
## S3 method for class 'cd_average_reporting_rate' tbl_sum(x, ...)## S3 method for class 'cd_average_reporting_rate' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with the S3 method. |
A character vector describing the content and purpose of the
cd_average_reporting_rate data.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_average_reporting_rate(data)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_average_reporting_rate(data)
cd_completeness_summary
Provides the header shown when a cd_completeness_summary object is printed. It labels the
table as the percentage of monthly values with complete (non-missing) data, by year, ahead of
the usual tibble header.
## S3 method for class 'cd_completeness_summary' tbl_sum(x, ...)## S3 method for class 'cd_completeness_summary' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with S3 methods. |
A character vector that summarizes the data content and purpose, specifically indicating the proportion of values that are complete across years.
## Not run: # Generate a summary of data completeness by year tbl_sum(cd_completeness_summary_object) ## End(Not run)## Not run: # Generate a summary of data completeness by year tbl_sum(cd_completeness_summary_object) ## End(Not run)
cd_district_outliers_summary
Provides a summary for the cd_district_outliers_summary object, indicating the percentage of districts
without extreme outliers for each indicator by year. This summary supports monitoring data quality across
districts by showing the proportion of non-extreme values across all indicators.
## S3 method for class 'cd_district_outliers_summary' tbl_sum(x, ...)## S3 method for class 'cd_district_outliers_summary' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with S3 methods. |
A character vector describing the purpose and content of the data, highlighting the percentage of districts with no extreme outliers for each indicator annually.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_district_outlier_summary(data)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_district_outlier_summary(data)
cd_district_ratios_summary ObjectProvides a customized summary for a cd_district_ratios_summary object, which
includes the percentage of districts meeting the adequacy criteria (e.g., ratios
within the range of 1.0 to 1.5) across specified indicator pairs by year. This
summary aids in monitoring health indicator alignment at a district level over time.
## S3 method for class 'cd_district_ratios_summary' tbl_sum(x, ...)## S3 method for class 'cd_district_ratios_summary' tbl_sum(x, ...)
x |
A |
... |
Additional arguments to support S3 method compatibility. |
A character vector providing a descriptive title indicating the percentage of districts with indicator ratios that meet adequacy criteria, aiding in data quality interpretation.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) ratios <- calculate_ratios_and_adequacy(data) # the summary is the header printed above the table calculate_district_ratios_summary(ratios)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) ratios <- calculate_ratios_and_adequacy(data) # the summary is the header printed above the table calculate_district_ratios_summary(ratios)
Provides a custom summary for the cd_district_reporting_rate object, displaying
a message with the threshold used in calculating district-level reporting rates by year.
This summary serves to validate which districts meet the defined threshold for reporting completeness.
## S3 method for class 'cd_district_reporting_rate' tbl_sum(x, ...)## S3 method for class 'cd_district_reporting_rate' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with the S3 method. |
A character vector describing the reporting threshold applied and summarizing district reporting rates by year.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table, with the threshold used calculate_district_reporting_rate(data, threshold = 90)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table, with the threshold used calculate_district_reporting_rate(data, threshold = 90)
tbl_sum.cd_indicator_coverage generates a summary label for national coverage estimates tables,
providing a clear indication of the data contents. This function is designed to be used as a custom
summary method for objects of class cd_indicator_coverage, creating a consistent table title for
outputs.
## S3 method for class 'cd_indicator_coverage' tbl_sum(x, ...)## S3 method for class 'cd_indicator_coverage' tbl_sum(x, ...)
x |
An object of class |
... |
Additional arguments passed to |
This function is part of the summary method hierarchy for cd_indicator_coverage objects.
By adding a specific table title ("National Coverage Estimates"), this function helps standardize
output tables, ensuring consistency in reports and summaries for national health coverage indicators.
A named character vector where the first element, "Table", is titled "National Coverage Estimates",
followed by the summary generated by the next method in the class hierarchy.
## Not run: # Assuming `data` is of class `cd_indicator_coverage` tbl_sum.cd_indicator_coverage(data) ## End(Not run)## Not run: # Assuming `data` is of class `cd_indicator_coverage` tbl_sum.cd_indicator_coverage(data) ## End(Not run)
cd_missing_district
Provides a custom summary for the cd_missing_district object,
showing the percentage of districts with complete (non-missing) data aggregated
by year. This summary helps users understand the distribution of data completeness
at the district level across time.
## S3 method for class 'cd_missing_district' tbl_sum(x, ...)## S3 method for class 'cd_missing_district' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with S3 methods. |
A character vector that summarizes the data content and purpose, indicating the percentage of districts with complete data across years.
## Not run: # Generate a summary of district-level data completeness by year tbl_sum(calculate_district_completeness_summary(data)) ## End(Not run)## Not run: # Generate a summary of district-level data completeness by year tbl_sum(calculate_district_completeness_summary(data)) ## End(Not run)
cd_outlier
Provides a custom summary for the cd_outlier object, displaying
the percentage of monthly indicator values not considered extreme outliers, aggregated by year.
This summary is essential for assessing data quality and trends across indicators.
## S3 method for class 'cd_outlier' tbl_sum(x, ...)## S3 method for class 'cd_outlier' tbl_sum(x, ...)
x |
A |
... |
Additional arguments for compatibility with S3 methods. |
A character vector summarizing the content and purpose of the data, indicating the proportion of values meeting the criteria for non-outliers by year.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_outliers_summary(data, admin_level = "national")data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) # the summary is the header printed above the table calculate_outliers_summary(data, admin_level = "national")
cd_population_metrics
The print header of the population table prepare_population_metrics() gives: the population, births and
under-ones from DHIS2, beside the UN's at national level.
## S3 method for class 'cd_population_metrics' tbl_sum(x, ...)## S3 method for class 'cd_population_metrics' tbl_sum(x, ...)
x |
A |
... |
Additional arguments (not used). |
A character vector: the table's title, the country and the default header.
cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # the summary is the header printed above the table cache$denominator_metricscache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) cache$set_national_estimates(list(sbr = 0.02)) cache$adjust_data() # the summary is the header printed above the table cache$denominator_metrics
cd_ratios_summary ObjectProvides a concise summary for a cd_ratios_summary object, which includes
the calculated indicator ratios across specified pairs (e.g., ANC1/Penta1,
Penta1/Penta3, OPV1/OPV3) by year. This summary facilitates understanding of
inter-indicator consistency over time.
## S3 method for class 'cd_ratios_summary' tbl_sum(x, ...)## S3 method for class 'cd_ratios_summary' tbl_sum(x, ...)
x |
A |
... |
Additional arguments to support S3 method compatibility. |
A character vector providing a descriptive title that clarifies the type of summary and the indicator ratios reported, to enhance interpretation when viewing the data.
data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) ratios <- calculate_ratios_and_adequacy(data) # the summary is the header printed above the table calculate_ratios_summary(ratios)data <- load_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) ratios <- calculate_ratios_and_adequacy(data) # the summary is the header printed above the table calculate_ratios_summary(ratios)
The upload zone of the wizard's Upload Data step, where the user gives the health facility
data the whole analysis runs on: an Excel file (.xls, .xlsx), a Stata file (.dta) or a
saved dataset (.rds). The server reads the file and makes the dataset (a
CacheConnection) that every other step works on. A file that cannot be read shows an error
banner under the zone. The zone's reset button removes the dataset, which locks the later
steps again. A button downloads the merged data as a Stata file. The Upload Data step counts
as complete once a dataset is loaded (see step_upload_complete()).
upload_box_ui(id, i18n, is_electron = FALSE) upload_box_server(id, i18n, cdsuite_file, is_electron = FALSE)upload_box_ui(id, i18n, is_electron = FALSE) upload_box_server(id, i18n, cdsuite_file, is_electron = FALSE)
id |
The module's id. |
i18n |
The app's translator (a |
is_electron |
|
cdsuite_file |
The path of the file the app was started with, a string, or
|
How a file is loaded depends on its type:
Excel: the sheets are read with load_excel_parts() and kept unmerged in the dataset
(wizard_parts) until the user presses Finish. The country is worked out from the admin
sheet and stored with set_wizard_country().
Stata: the file is loaded with load_cache_data(), without validation. A copy is saved when
the user presses Finish, as for Excel.
.rds: a saved dataset is loaded with load_cache_data() too, and needs no walkthrough.
A Stata file or a saved dataset built for another indicator group than the app's is refused
(cd_wizard_check_group()).
An Excel or Stata file that has a saved copy from an earlier Finish (named by
cd_saved_copy_name(), in the dataset folder) loads that copy in its place, so the user does
not go through the walkthrough again. When the copy cannot be read, the original file is
loaded. The dataset folder is the folder of cdsuite_file when the app was started with a
file, and otherwise datasets under tools::R_user_dir("cd2030", "data").
When the app is started with a file (is_electron = TRUE) there is no upload zone: the
server loads cdsuite_file once at startup and shows a success or an error banner.
upload_box_ui() returns the UI as Shiny tags: the upload zone (left out when
is_electron is TRUE), the placeholder for the status banner and the download button.
It has no card of its own. upload_box_server() returns a list with three elements:
cache: a reactive that returns the dataset, a CacheConnection, or NULL when none is
loaded;
requires_walkthrough: a reactive value that is TRUE when the wizard must be walked
through step by step, and FALSE when a saved dataset (.rds) was loaded;
source_path: a reactive value that holds the path Finish saves the dataset next to
(the dataset folder and the file's name), or NULL when a saved dataset was loaded or
nothing is loaded.
## Not run: # in a module's ui: the user picks the file in the page upload_box_ui(ns("upload_box"), i18n) # in its server upload <- upload_box_server("upload_box", i18n, cdsuite_file = NA_character_) observe({ req(upload$cache()) message("Loaded ", upload$cache()$country, "; walkthrough: ", upload$requires_walkthrough()) }) # an app started with a file to load: no upload zone, the file is loaded at startup upload_box_ui(ns("upload_box"), i18n, is_electron = TRUE) upload <- upload_box_server("upload_box", i18n, "C:/data/Kenya.xlsx", is_electron = TRUE) ## End(Not run)## Not run: # in a module's ui: the user picks the file in the page upload_box_ui(ns("upload_box"), i18n) # in its server upload <- upload_box_server("upload_box", i18n, cdsuite_file = NA_character_) observe({ req(upload$cache()) message("Loaded ", upload$cache()$country, "; walkthrough: ", upload$requires_walkthrough()) }) # an app started with a file to load: no upload zone, the file is loaded at startup upload_box_ui(ns("upload_box"), i18n, is_electron = TRUE) upload <- upload_box_server("upload_box", i18n, "C:/data/Kenya.xlsx", is_electron = TRUE) ## End(Not run)
Temporarily suppress messages by enabling quiet mode within the provided code block.
Temporarily suppress messages within the specified environment.
with_cd_quiet(code) local_cd_quiet(env = parent.frame())with_cd_quiet(code) local_cd_quiet(env = parent.frame())
code |
Code to execute quietly |
env |
The environment to use for scoping. |
No return value, called for side effects
No return value, called for side effects.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") # no progress messages while the data loads data <- with_cd_quiet(load_data(path)) # quiet until the function returns load_quietly <- function(path) { local_cd_quiet() load_data(path) } data <- load_quietly(path)path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") # no progress messages while the data loads data <- with_cd_quiet(load_data(path)) # quiet until the function returns load_quietly <- function(path) { local_cd_quiet() load_data(path) } data <- load_quietly(path)
Returns every field of one kind from the app's wizard configuration
(cd_wizard_config()$national_rates_groups), across all groups, in display order.
wizard_fields(kind)wizard_fields(kind)
kind |
The kind of field to return: |
A list of field descriptions, as made by cd_wizard_survey_field() or
cd_wizard_rate_field(). The list is empty when the configuration has no field of that
kind.
old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) vapply(wizard_fields("survey"), function(f) f$id, character(1)) vapply(wizard_fields("rate"), function(f) f$id, character(1)) options(old)old <- options(cd2030.wizard = list(national_rates_groups = list( cd_wizard_field_group("title_upload_group_maternal", "sub_upload_group_maternal", cd_wizard_survey_field("anc4_prop", "anc4", "title_upload_anc4_survey"), cd_wizard_national_rate_fields() ) ))) vapply(wizard_fields("survey"), function(f) f$id, character(1)) vapply(wizard_fields("rate"), function(f) f$id, character(1)) options(old)
The page the wizard shows in place of its steps once a dataset is finished: after the user
presses Finish, or when a saved dataset (.rds) is loaded. It has a banner that says the
dataset is ready, with a button that opens the Reporting Rate page ("reporting_rate"), and
one row per wizard step. Each row gives the step's title, an "optional" badge when the step
is not required, a one-line summary of what the dataset holds for that step, and an Edit
button that opens the step. Nothing is saved to the dataset here.
wizard_landing_ui(id) wizard_landing_server(id, cache, step_defs, i18n, on_edit, just_finished)wizard_landing_ui(id) wizard_landing_server(id, cache, step_defs, i18n, on_edit, just_finished)
id |
The module's id. |
cache |
A reactive that returns the dataset, a CacheConnection. |
step_defs |
The wizard's steps, a list with the structure of wizard_step_defs. The page shows one row per step, in this order. |
i18n |
The app's translator (a |
on_edit |
A function of one argument, the key of a step. The page calls it when the user presses that step's Edit button; the caller uses it to open the step. |
just_finished |
A reactive that returns |
wizard_steps_server() shows this page and starts its server; an app does not normally call
either function itself.
wizard_landing_ui() returns the UI as Shiny tags: the placeholders for the banner
and the rows. wizard_landing_server() is called for its side effects and returns nothing
useful.
## Not run: # in a module's server, as wizard_steps_server() uses it output$body <- renderUI(wizard_landing_ui(ns("landing"))) current_step <- reactiveVal("upload") wizard_landing_server( "landing", cache = cache, step_defs = wizard_step_defs, i18n = i18n, on_edit = function(step_key) current_step(step_key), just_finished = reactive(FALSE) ) ## End(Not run)## Not run: # in a module's server, as wizard_steps_server() uses it output$body <- renderUI(wizard_landing_ui(ns("landing"))) current_step <- reactiveVal("upload") wizard_landing_server( "landing", cache = cache, step_defs = wizard_step_defs, i18n = i18n, on_edit = function(step_key) current_step(step_key), just_finished = reactive(FALSE) ) ## End(Not run)
The definition of the wizard's seven steps, in the order the user goes through them: Upload
Data, Data Quality, Survey Files, National Rates, Shapefile, Map Survey Files and Map
Shapefile Names. compute_step_states() turns it into the state of each step for a dataset.
Survey Files and Shapefile are optional; the other five are required.
wizard_step_defswizard_step_defs
A list of seven lists, one per step. Each has:
key: the step's key, a string: "upload", "quality", "survey_files",
"national_rates", "shapefile", "survey_mapping" or "map_mapping".
title_key: the translation key of the step's title.
required: TRUE when the step must be complete before the user can go on.
complete_fn: a function of the dataset that returns TRUE when the step is complete
(see step_upload_complete()).
touched_fn (the Shapefile step only): a function of the dataset that returns TRUE when
the user has done something on the step.
relevant_fn (the two mapping steps only): a function of the dataset whose result
compute_step_states() reports as relevant.
Survey Files comes before National Rates because an uploaded national survey fills in most of the National Rates fields; the user then only has to check them.
vapply(wizard_step_defs, function(s) s$key, character(1)) vapply(wizard_step_defs, function(s) s$required, logical(1)) # test one step on a dataset cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) wizard_step_defs[[1]]$complete_fn(cache)vapply(wizard_step_defs, function(s) s$key, character(1)) vapply(wizard_step_defs, function(s) s$required, logical(1)) # test one step on a dataset cache <- load_cache_data(system.file("extdata", "kenya.xlsx", package = "cd2030.core")) wizard_step_defs[[1]]$complete_fn(cache)
The frame of the Load Data wizard. It shows the row of steps, the page of the current step,
and a footer with Back and Continue buttons, and it decides which step the user may open
(compute_step_states()). A newly loaded Excel or Stata file is walked through step by step:
a step opens once the user has moved on from the one before it, and a required step must be
complete before Continue is enabled. An optional step the user has not touched offers "Skip"
in place of "Continue". The last step's button is Finish. A saved dataset (.rds) skips the
walkthrough and opens on the summary page (wizard_landing_ui()), from which any step can be
opened for editing.
wizard_steps_ui(id) wizard_steps_server( id, i18n, cache, requires_walkthrough, panels, source_path, active, step_defs = wizard_step_defs )wizard_steps_ui(id) wizard_steps_server( id, i18n, cache, requires_walkthrough, panels, source_path, active, step_defs = wizard_step_defs )
id |
The module's id. |
i18n |
The app's translator (a |
cache |
A reactive that returns the dataset, a CacheConnection, or |
requires_walkthrough |
A reactive that returns |
panels |
The pages of the steps: a list with one element per step of |
source_path |
A reactive that returns the path Finish saves the dataset next to, a
string, or |
active |
A reactive that returns |
step_defs |
The wizard's steps, a list with the structure of wizard_step_defs, which is the default. |
Finish. On a dataset whose sheets are not merged yet (cache()$wizard_parts), and whose
blocking quality checks pass, Finish:
merges the sheets with merge_and_standardize() for the app's indicator group, adds a key
per admin level 1 area, and saves the result with cache()$set_countdown_data();
adds the same keys to the saved survey and shapefile name mappings
(cache()$set_survey_mapping(), cache()$set_map_mapping());
marks the dataset as finished with cache()$set_quality_confirmed(TRUE);
sets where the dataset is saved, with cache()$set_cache_path(): the folder of
source_path() and the name cd_saved_copy_name() gives;
keeps the quality check results with cache()$set_wizard_quality_results(), then removes
the unmerged sheets with cache()$clear_wizard_parts().
When the merge fails, an error notification shows and the wizard stays on the last step. Otherwise the wizard shows the summary page. A dataset that has no unmerged sheets (one loaded from a Stata file) is merged already: Finish marks it finished and sets where it is saved, the same way.
Editing. A dataset that is finished (loaded from a saved copy, or
cache()$quality_confirmed is TRUE) is in edit mode. The footer then has a button back to
the summary page and a button that opens the Reporting Rate page ("reporting_rate").
Coming back to the Load Data screen from another page shows the summary page again when
cache()$quality_confirmed is TRUE.
wizard_steps_ui() returns the UI as Shiny tags: the placeholder the server fills
with the wizard or the summary page. wizard_steps_server() returns a list with two
elements:
edit_mode: a reactive that is TRUE when a finished dataset is being edited;
current_step: a reactive value that holds the key of the current step.
## Not run: # in the ui of the Load Data screen wizard_steps_ui(ns("wizard")) # in its server: one page per step of wizard_step_defs, built with the screen's own ns() upload <- upload_box_server("upload_box", i18n, cdsuite_file = NA_character_) panels <- list( list(key = "upload", ui = upload_box_ui(ns("upload_box"), i18n)), list(key = "quality", ui = data_quality_ui(ns("data_quality"), i18n)), list(key = "survey_files", ui = survey_upload_ui(ns("survey_upload"), i18n)), list(key = "national_rates", ui = national_rates_ui(ns("national_rates"), i18n)), list(key = "shapefile", ui = shapefile_step_ui(ns("shapefile_step"), i18n)), list(key = "survey_mapping", ui = map_survey_ui(ns("map_survey"), i18n)), list(key = "map_mapping", ui = map_shapefile_ui(ns("map_shapefile"), i18n)) ) wizard <- wizard_steps_server( "wizard", i18n = i18n, cache = upload$cache, requires_walkthrough = upload$requires_walkthrough, panels = panels, source_path = upload$source_path, active = active ) observe(message("On step ", wizard$current_step())) ## End(Not run)## Not run: # in the ui of the Load Data screen wizard_steps_ui(ns("wizard")) # in its server: one page per step of wizard_step_defs, built with the screen's own ns() upload <- upload_box_server("upload_box", i18n, cdsuite_file = NA_character_) panels <- list( list(key = "upload", ui = upload_box_ui(ns("upload_box"), i18n)), list(key = "quality", ui = data_quality_ui(ns("data_quality"), i18n)), list(key = "survey_files", ui = survey_upload_ui(ns("survey_upload"), i18n)), list(key = "national_rates", ui = national_rates_ui(ns("national_rates"), i18n)), list(key = "shapefile", ui = shapefile_step_ui(ns("shapefile_step"), i18n)), list(key = "survey_mapping", ui = map_survey_ui(ns("map_survey"), i18n)), list(key = "map_mapping", ui = map_shapefile_ui(ns("map_shapefile"), i18n)) ) wizard <- wizard_steps_server( "wizard", i18n = i18n, cache = upload$cache, requires_walkthrough = upload$requires_walkthrough, panels = panels, source_path = upload$source_path, active = active ) observe(message("On step ", wizard$current_step())) ## End(Not run)
Two sheets: Summary (each check, whether it passed, how many issues) and Issues (one row per issue).
write_quality_issues(results, path, labels = NULL)write_quality_issues(results, path, labels = NULL)
results |
A named list. What |
path |
Where to write the |
labels |
An optional named character vector that maps a check's key ( |
path, invisibly.
path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) results <- run_all_quality_checks(cache) file <- write_quality_issues(results, tempfile(fileext = ".xlsx")) openxlsx::read.xlsx(file, sheet = "Issues")path <- system.file("extdata", "kenya.xlsx", package = "cd2030.core") cache <- load_cache_data(path) results <- run_all_quality_checks(cache) file <- write_quality_issues(results, tempfile(fileext = ".xlsx")) openxlsx::read.xlsx(file, sheet = "Issues")