## ----include = FALSE----------------------------------------------------------
is_srvyr_ready <- requireNamespace("srvyr", quietly = TRUE)
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = is_srvyr_ready
)

## ----setup-packages, message=FALSE, warning=FALSE-----------------------------
library(SurveyNCD)
library(dplyr)
library(srvyr)

## ----anthro-clean-------------------------------------------------------------
# Simulating raw survey data with a missing flag (9999)
raw_survey_data <- tibble(
  cluster_id = c(1, 1, 2, 2),
  strata = c(1, 1, 2, 2),
  sample_weight = c(1.2, 0.8, 1.1, 0.9),
  wealth_score = c(-1.5, -0.2, 0.5, 1.8),
  raw_hw70 = c(-310, -254, 50, 9999) # Raw Height-for-Age
)

# Apply the SurveyNCD cleaning function
cleaned_data <- raw_survey_data %>%
  mutate(
    stunting_category = who_anthro_score(raw_hw70, indicator = "stunting"),
    is_stunted = case_when(
      stunting_category %in% c("Severe stunting", "Moderate stunting") ~ 1,
      stunting_category == "Normal stunting" ~ 0,
      TRUE ~ NA_real_
    )
  )

cleaned_data %>% select(raw_hw70, stunting_category, is_stunted)

## ----survey-design------------------------------------------------------------
svy_design <- cleaned_data %>%
  as_survey_design(
    ids = cluster_id,
    strata = strata,
    weights = sample_weight
  )

## ----calc-ci------------------------------------------------------------------
stunting_inequality <- svy_design %>%
  survey_concentration_index(
    outcome = is_stunted,
    wealth = wealth_score
  )

print(stunting_inequality)

