Shannon Diversity Index for Food Consumption in India
1. Introduction
1.1 Motivation
The Shannon Diversity Index provides a single summary of dietary quality that captures both variety and adequacy. Unlike simple adequacy ratios, it distinguishes between a balanced diet and one concentrated in a few food groups. Individual food item models tell us what people eat, but not how balanced their diet is. The Shannon diversity index (Shannon, 1948)[1] addresses this by summarizing the evenness of consumption across food groups, combined with a requirement-adequacy adjustment.
This methodology document outlines the construction, modeling, and prediction of the Shannon Diversity Index for food consumption in India, using household-level data from the Household Consumer Expenditure Survey (HCES) 2011–12 and 2023–24, benchmarked against ICMR-NIN Recommended Dietary Allowances.
1.2 Food Categories Analyzed
The analysis covers ten food categories based on the ICMR-NIN recommended balanced diet for an adult woman (55 kg, moderately active, non-lactating):
| Food Category | Daily Requirement (grams) |
|---|---|
| Cereals & Millets | 280 |
| Green Leafy Vegetables | 100 |
| Other Vegetables | 200 |
| Roots & Tubers (excl. potatoes) | 100 |
| Fruits | 100 |
| Milk & Milk Products | 300 |
| Fats & Oils | 25 |
| Oilseeds & Nuts | 40 |
| Pulses & Beans | 95 (combined with Flesh) |
| Flesh Foods | 95 (combined with Pulses) |
Note: Pulses & Beans and Flesh Foods share a combined requirement of 95 grams per day. In the gram-based construction, we allocate this flexibly based on household consumption patterns.
2. Gram-Based Shannon Diversity Index
2.1 Construction (Step by Step)
The gram-based Shannon Diversity Index is constructed through the following sequential steps:
- Per-AFE Intake: Divide household-level food quantities by Adult Female Equivalent (AFE) household size to obtain grams per day per AFE for each of the 9 food groups.
- Cap at Requirement: Set \(a_i = \min(\text{intake}_i, \text{requirement}_i)\) for each group \(i\). Eating more than required does not inflate the diversity score.
- Compute Shares: Calculate \(p_i = \frac{a_i}{\sum_j a_j}\) — the proportion of capped intake from each food group.
- Shannon Entropy: Compute \(H = -\sum_i p_i \log(p_i)\), where higher values indicate more even distribution across groups.
- Adequacy Adjustment: For each food group, calculate \(\min(\text{intake}_i / \text{requirement}_i, 1)\), then average across all groups to obtain \(A\). This penalizes diets that are diverse but nutritionally insufficient.
- Cereal Adjustment: Indian diets are typically dominated by cereals. Even after capping at the requirement (Step 2), cereals still command a large share because their requirement (280 g/day) is much larger than most other food groups (e.g., Fats & Oils at 25 g, Oilseeds & Nuts at 40 g). This means a household could score reasonably well on Shannon entropy simply because it eats a lot of rice or wheat — even if it barely consumes any vegetables, fruits, or protein sources. The cereal adjustment corrects for this by penalizing households whose cereal share exceeds what would be expected under a balanced, requirement-proportional diet.
First, compute the expected cereal share under the ICMR-NIN requirements: \(s^{*}_{\mathrm{cereal}} = \dfrac{r_{\mathrm{cereal}}}{\sum_j r_j} = \dfrac{280}{1240} \approx 0.226\). This is the share cereals would have if every food group were consumed at exactly its required level.
Then, compute how much the household's actual cereal share (from Step 3) exceeds this benchmark: \(\delta_{\mathrm{cereal}} = \max\!\left(p_{\mathrm{cereal}} - s^{*}_{\mathrm{cereal}},\; 0\right)\). If the household's cereal share is at or below the expected share, \(\delta_{\mathrm{cereal}} = 0\) and no penalty is applied.
Finally, convert the excess share into an exponentially decaying penalty: \(C = \exp\!\left(-3 \times \delta_{\mathrm{cereal}}\right)\). The multiplier of 3 controls the severity: a cereal share 10 percentage points above the benchmark yields \(C = e^{-0.3} \approx 0.74\) (a 26% penalty), while a share 20 points above yields \(C = e^{-0.6} \approx 0.55\) (a 45% penalty). The exponential form ensures \(C \in (0, 1]\), with \(C = 1\) when cereal consumption is proportionate and \(C \to 0\) as cereal dominance becomes extreme.
In practice, this adjustment matters most for low-income households that spend the bulk of their food budget on rice or wheat and consume negligible amounts of fruits, vegetables, dairy, and protein-rich foods. Without this correction, such households would receive misleadingly high diversity scores.
- Final Index: Calculate \(H_{\text{adj}} = H \times A \times C\).
2.2 Mathematical Formulation
Let \(q_i\) denote the intake (in grams per day per AFE) of food group \(i\), and \(r_i\) denote the ICMR-NIN requirement for that group.
Shannon Entropy:
Adequacy Score:
Cereal Penalty:
Combined Diversity Index:
2.3 Interpreting the Components
The Shannon Diversity Index combines three complementary dimensions of diet quality:
| Component | What It Captures | Range |
|---|---|---|
| \(H\) (Shannon) | Evenness of consumption across food groups | \([0, H^*]\) |
| \(A\) (Adequacy) | Whether each food group meets its requirement | \([0, 1]\) |
| \(C\) (Cereal Penalty) | Penalizes cereal over-dependence | \((0, 1]\) |
| \(H_{\text{adj}}\) | Overall dietary quality | \([0, H^*]\) |
The theoretical maximum of the Shannon entropy for \(K = 9\) food groups is \(\ln(9) \approx 2.20\), attained when all shares are equal (\(p_i = 1/9\)). Because intakes are capped at requirements (Step 2) and requirements differ across food groups, a household meeting all requirements exactly will have shares \(p_i = r_i / \sum_j r_j\), which are not uniform. Therefore the effective maximum under this construction is \(H^* = -\sum (r_i / \sum r_j)\,\ln(r_i / \sum r_j) \approx 1.97 < \ln(9)\). A household consuming only rice has \(H \approx 0\) (no diversity); \ For the logit-scale modeling, however, the index is normalized by \(\log K\) (the uniform-shares maximum), not by \(H^{*}\); a perfectly balanced, requirement-meeting diet therefore maps to about \(H^{*}/\log K \approx 0.90\) on the 0–1 scale rather than exactly 1.
3. Ratio-Based Shannon Diversity Index (Alternative)
3.1 Motivation
In the gram-based construction, food groups with large requirements (e.g., cereals at 280g) dominate the shares \(p_i\), making it harder for smaller-requirement groups (e.g., oilseeds at 40g) to influence diversity. The ratio-based alternative normalizes each intake by its requirement first, placing all food groups on a common 0–1 scale regardless of requirement magnitude.
3.2 Construction (Step by Step)
The ratio-based construction follows a similar sequence, with one key modification:
- Per-AFE Intake: Same as gram-based.
- Ratio and Cap: Set \(a_i = \min(q_i / r_i, 1)\) for each group. This is the adequacy ratio, capped at 1.
- Compute Shares: Calculate \(p_i = \frac{a_i}{\sum_j a_j}\) — the proportion of capped adequacy ratios.
- Shannon Entropy: Compute \(H = -\sum_i p_i \log(p_i)\).
- Adequacy Adjustment: Same as gram-based: \(A = \frac{1}{K} \sum_i \min(q_i/r_i, 1)\).
- Final index: Calculate \(H_{\text{adj}}^{\text{ratio}} = H \times A\); a cereal-adjusted variant \(H \times A \times C\) is also formed and modeled (see §3.5).
3.3 Mathematical Formulation
3.4 Key Differences from Gram-Based
| Feature | Gram-Based | Ratio-Based |
|---|---|---|
| Capping Rule | \(a_i = \min(q_i, r_i)\) | \(a_i = \min(q_i/r_i, 1)\) |
| Scale | Grams per day | Proportional (0–1) |
| Share Interpretation | Gram proportion of capped intake | Proportion of capped adequacy ratios |
| Cereal Dominance | High (large requirement) | Moderate (equal max of 1.0) |
| Cereal Adjustment | \nYes (reads capped-gram shares) | \nYes, but milder (reads capped-ratio shares) |
| Max Shannon | \(H^* \approx 1.97\) (requirement-weighted) | \(\ln(9) \approx 2.20\) (uniform when all groups fully met) |
3.5 Cereal Adjustment on the Ratio Basis
The ratio basis is also given a cereal penalty in the current pipeline, exactly
parallel to the gram basis. Using the ratio-basis cereal share
\(p^{\text{ratio}}_{\text{cereal}}\), the excess over the requirement share
\(s^{*}_{\text{cereal}} = r_{\text{cereal}}/\sum_j r_j\) drives the same penalty
\(C = \exp(-3\,\delta)\), yielding a ratio cereal-adjusted index \(H\cdot A\cdot C\) fitted
as its own model (model_shannon_cereal_adj). Each basis therefore exposes a plain, an
adjusted, and a cereal-adjusted Shannon measure.
What differs between the bases is only the share the penalty reads — capped-ratio shares versus capped-gram shares. Because the ratio construction caps each group's adequacy at 1 before forming shares, cereals cannot dominate the share denominator as strongly as under grams, so the ratio cereal penalty is typically milder — but it is not omitted.
4. Why Shannon Over Adequacy Ratio?
4.1 MAR Cannot Distinguish Balance
The simple Mean Adequacy Ratio (MAR) is defined as \(\text{MAR} = \frac{1}{K} \sum_i \min(q_i/r_i, 1)\) — it captures only the first moment of the adequacy distribution. Consider three households:
| Household | Cereal Adequacy | Veg Adequacy | Protein Adequacy | MAR | Shannon \(H_{\text{adj}}\) |
|---|---|---|---|---|---|
| A | 1.0 | 0.5 | 0.2 | 0.57 | 0.42 |
| B | 0.8 | 0.6 | 0.5 | 0.63 | 0.58 |
| C | 0.6 | 0.6 | 0.6 | 0.60 | 0.55 |
Households B and C have similar MAR values, yet their diet distributions are quite different: B has one adequate group and two under-consumed; C has all three groups equally under-consumed. The Shannon index captures this distributional difference through the entropy component \(H\).
4.2 Shannon Captures Distribution
The Shannon entropy \(H\) measures the distributional shape — how evenly consumption is spread. Two diets with identical adequacy scores but different shapes (one concentrated in one group, one spread across groups) will have different Shannon values. The combined index \(H_{\text{adj}} = H \times A \times C\) thus captures both the level of intake (via \(A\)) and its distribution (via \(H\)).
4.3 Policy Relevance
Interventions to improve diet quality depend on the diagnostic:
- Low \(A\), High \(H\): Diet is well-balanced but insufficient. Increase overall food intake through income/food subsidies.
- Moderate \(A\), Low \(H\): Diet relies heavily on few foods. Diversification campaigns needed.
- Low \(A\), Low \(H\): Both levels and diversity are inadequate. Comprehensive nutrition intervention needed.
5. Modeling the Diversity Index
5.1 Data Preparation
The analysis uses data from HCES 2011–12 and 2023–24. Key covariates include:
| Covariate | Description | Role |
|---|---|---|
log_mpce_real_afe |
Log of real MPCE per AFE (2023–24 prices) | Global Engel curve |
state_code |
State identifier | Geographic variation |
sector |
Rural / Urban | Urbanization effect |
nss_region |
NSS statistical region | Regional variation |
reg_sector |
Regional × Sector interaction | Regional urbanization patterns |
social |
Social group (SC/ST/OBC/Others) | Social equity |
rel |
Religion | Dietary preferences |
child |
Binary: presence of children | Household composition |
female_headed |
Binary: female household head | Gender dimension |
seasonal |
Season of survey (coded by round) | Seasonal variation |
5.2 Transformation to the Real Line
The requirement-adjusted Shannon index \(H_{\text{adj}}\) is bounded, \(H_{\text{adj}} \in [0,\ \log K]\), where \(K\) is the number of food groups (so \(\log K\) is the maximum possible entropy). To model it with a Gaussian GAM we apply a logit transformation:
- Normalize by the maximum: \(\tilde{H}_{\text{adj}} = \frac{H_{\text{adj}}}{\log K} \in [0, 1]\)
- Clip: Clip to \([\varepsilon, 1-\varepsilon]\) where \(\varepsilon = 10^{-6}\) (prevents infinities)
- Logit transform: \(y = \log\left(\frac{\tilde{H}_{\text{adj}}}{1 - \tilde{H}_{\text{adj}}}\right) \in \mathbb{R}\)
After modeling on the logit scale, predictions are back-transformed to the original scale via the inverse logit and scaling.
5.3 GAM Specification
The Shannon responses reuse the exact same right-hand side as the
food-consumption models (the shared make_formula() builder), with the
seasonal terms switched on. Writing \(\ell = \log(\text{MPCE}^{\text{AFE},2023})\)
for log real per-AFE expenditure (2023 ₹), the specification is:
z ~ sector + child + female_headed + social + rel # parametric fixed effects
+ s(log_mpce_real_afe, k = 10) # global income (Engel) curve
+ s(state_code, bs = "re") # state random intercept
+ s(log_mpce_real_afe, state_code, bs = "fs", k = 5, m = 1) # state income deviations
+ s(log_mpce_real_afe, by = child_o, k = 5) # demographic income-gradient
+ s(log_mpce_real_afe, by = female_headed_o, k = 5) # DIFFERENCE smooths
+ s(log_mpce_real_afe, by = social_o, k = 5)
+ s(log_mpce_real_afe, by = rel_o, k = 5)
+ s(nss_region, bs = "re") # region random intercept
+ s(reg_sector, bs = "re") # region x sector random intercept
+ seasonal + s(log_mpce_real_afe, by = seasonal_o, k = 5) # seasonal terms
The five kinds of terms are:
- Parametric fixed effects —
sector,child,female_headed,social,rel: constant level shifts in the response, not random effects. - Global income (Engel) curve —
s(ℓ, k = 10): a thin-plate spline for the reference levels of the factors above. - State income deviations —
s(ℓ, state_code, bs = "fs", k = 5, m = 1): a factor-smooth giving each state its own income curve, shrunk toward the global one. - Demographic income-gradient shifts — ordered-factor
difference smooths
s(ℓ, by = g_o)for child, female-headship, social group and religion. - Geographic random intercepts —
s(state_code),s(nss_region),s(reg_sector)(allbs = "re"), wherereg_sector = nss_region × sector. These partially pool small groups.
Across the seven models below only the response changes; this right-hand side is identical.
5.4 Estimation Details
The model is estimated using mgcv::bam() with the following settings:
| Parameter | Value | Rationale |
|---|---|---|
| Smoothing Method | fREML (fast REML) | Efficient for large datasets |
discrete=TRUE |
TRUE | Reduces memory for large \(n\) |
gamma |
1.4 | Slight over-smoothing for stability |
select=TRUE |
TRUE | Allows shrinkage of individual terms toward zero |
| Family | Gaussian | Appropriate for logit-transformed \(y\) |
5.5 Models Estimated
For each survey round the pipeline fits seven Gaussian GAMs on logit-normalized responses — three on the ratio basis, three on the gram basis, and one shared Mean Adequacy Ratio (MAR) model:
| Model | Response (before logit / ÷ log K) | Meaning |
|---|---|---|
model_shannon_food | \(H\cdot A\) | ratio, adjusted |
model_shannon_plain | \(H\) | ratio, plain Shannon |
model_shannon_cereal_adj | \(H\cdot A\cdot C\) | ratio, cereal-adjusted |
model_shannon_gram | \(H_g\cdot A\) | gram, adjusted |
model_shannon_gram_plain | \(H_g\) | gram, plain Shannon |
model_shannon_gram_cereal_adj | \(H_g\cdot A\cdot C_g\) | gram, cereal-adjusted |
model_mar | \(A\) (as qlogis(A)) | Mean Adequacy Ratio (shared) |
Fourteen fits in all across the two rounds. From these, the dashboard exposes six measures per basis, each with a 95% credible interval:
| Key | Definition | Source |
|---|---|---|
m | plogis(ηz) | modeled adjusted, \(H\cdot A\) normalized |
mp | plogis(ηzp) × log K | modeled plain Shannon, raw scale |
mm | plogis(ηzm) | modeled MAR (shared across bases) |
mr | mp × mm | raw adjusted (product form) |
mca | plogis(ηzc) | modeled cereal-adjusted (its own bam) |
ecs | weighted mean excess-cereal share | descriptive (not modeled) |
The two bases are written to two dashboard files — data_shannon_food_new.js
(ratio) and data_shannon_food_gram_new.js (gram). Only mm (MAR) is
identical across bases. mca is a separate fitted model, not the derived
product \(m\cdot e^{-3\,\text{ecs}}\), so it carries a genuine model interval;
ecs stays a descriptive survey-weighted quantity.
6. Prediction Grid Construction
Before generating predictions, the analysis constructs standardized prediction populations that control for confounding when comparing groups. This is a critical step: raw comparisons between, say, rural and urban diversity would conflate the true sector effect with differences in the geographic and demographic composition of each sector.
6.1 The Standardization Problem
Consider comparing dietary diversity between rural and urban India. Urban households are disproportionately located in richer states (Maharashtra, Karnataka) and have different demographic profiles (fewer children, different religious composition). A naive rural–urban comparison would mix three effects: the actual sector effect on diversity, geographic composition differences, and demographic composition differences.
Standardization solves this by constructing a counterfactual population in which all non-focal variables are held at the same national distribution.
6.2 Grid Construction Logic (g-computation)
The comparison uses g-computation (standardization by prediction), not a re-weighted synthetic grid. The idea is simple: take the entire observed national sample of households — each with its real expenditure, sector, demographics and location — and, for each level of the focal variable, build a counterfactual copy of that same sample in which every household is assigned that level, holding all other covariates at their observed values. The fitted model predicts each household's diversity index, and these are averaged (survey-weighted) within each expenditure decile.
Because the same national population underlies every level, the income and demographic composition is identical across levels by construction. Any difference between, say, two states is therefore attributable to the focal variable alone — it cannot come from one state being richer or having more children, because those are held fixed at the national mix.
The only subtlety is the derived geographic terms. Because
reg_sector = nss_region × sector (and, for a state counterfactual,
nss_region itself) become inconsistent once geography is reassigned — a
household's real region no longer matches its counterfactual state — the code
excludes those terms from the counterfactual prediction so they contribute nothing. Which
terms are dropped depends on the comparison:
Standardization by comparison type (g-computation):
STATE set state_code = X for ALL households
-> drop s(nss_region) and s(reg_sector) [stale under counterfactual]
-> each household keeps its own income, sector, demographics
NSS REGION set nss_region = R for ALL households
-> also set state_code = parent state of R (first 2 digits of code)
-> drop s(reg_sector)
SECTOR set sector = rural / urban for ALL households
-> drop s(reg_sector)
DEMOGRAPHIC set social / religion / child / female_headed = level for ALL
-> geography untouched; nothing excluded
What “drop” means. A household's prediction is a
sum of pieces — global mean + income curve + state effect + region effect + region×sector
effect + demographics. To drop a term (predict(…, exclude = …))
is to leave it out of that sum, i.e. set its contribution to zero. Since s(nss_region)
and s(reg_sector) are random-effect terms (deviations centred at zero),
excluding one simply uses its neutral / average value — no region-specific bump. We drop them
under a geographic counterfactual because each household still carries its real region,
which is now inconsistent with the reassigned state (and a rebuilt region×sector can be a
combination never seen in fitting). The result is “the state at the average region,” net
of within-state region and region×sector variation. The parametric sector main
effect is not dropped — only the region×sector random deviation is — so
the rural/urban level shift is retained.
6.3 Worked Example: Comparing States and NSS Regions
State comparison — Bihar vs. Punjab. Begin with all \(N\) households in the survey round, carrying their actual expenditure, sector, religion, household composition and location.
Make a counterfactual copy in which
state_code = Biharfor every household — income, sector and demographics are left untouched. Because each household's real NSS region no longer belongs to Bihar, drop thes(nss_region)ands(reg_sector)terms from the prediction.Predict each household's diversity index. Every prediction combines that household's own income and demographics with Bihar's state intercept and Bihar's state-specific income (Engel) curve.
Average the predictions with survey weights within each expenditure decile (and once more overall, at the population-mean income, for the “Overall” summary row).
Repeat the whole procedure with
state_code = Punjab.
The Bihar and Punjab curves are computed on the identical national population, so their difference is the pure state effect: what diversity would look like if the whole country faced Bihar's versus Punjab's state-level conditions, at one common income and demographic mix.
NSS region comparison — “BR: Central” vs. “PB: Northern”.
The procedure is identical, but the focal variable is nss_region: every household is
assigned the chosen region. Because a region code's first two digits identify its state, the code
simultaneously sets state_code to that region's parent state (e.g. BR ->
Bihar), so the region effect and its parent-state effect move together; only s(reg_sector)
is dropped. The contrast is therefore the combined region-plus-state effect, again net of income and
demographic composition.
Why not simply compare the households actually living in each state? Because states differ in income and demographics: a raw Bihar–Punjab gap would blend the state effect with Punjab being richer and Bihar having a younger population. Assigning the same national population to each state strips out that confounding. This is the same mechanism behind the Christian flesh-food pattern — the unadjusted figure reflects where a group lives, while the standardized figure holds geography at the national mix.
What about income — is it standardized too? No. Income is not reassigned; only the focal variable is. Each household keeps its actual MPCE, and every prediction is made at that real income. The expenditure decile is purely a reporting grouping: households are binned by their real (national) income decile, and the counterfactual predictions are survey-weight-averaged within each bin. Because the compared levels (Bihar, Punjab) use the very same households, the income distribution inside a given decile is identical across levels — which is precisely what “compared at the same income” means. A separate “Overall” row aggregates across all deciles at each level's population-mean income, giving the marginal group summary shown in the dashboard cards.
6.4 Expenditure Binning and Income
For the standardized comparison, households are assigned to expenditure deciles cut on the national real-MPCE (per-AFE, 2023 ₹) distribution — the same cutpoints for every level being compared, so a given decile denotes the same income band across, say, Bihar and Punjab. (The purely descriptive, unadjusted group breakdowns instead cut deciles within each group.)
| Bin | Label | Definition |
|---|---|---|
| 1 | 0–10 | Below the 10th percentile of the national real-MPCE distribution |
| 2 | 10–20 | 10th to 20th percentile |
| … | … | … |
| 10 | 90–100 | Above the 90th percentile |
| Overall | Overall | Full population (weighted-mean MPCE) |
7. Posterior Simulation and Uncertainty Propagation
7.1 Covariance and the Clustered Sandwich
After fitting, the penalized covariance \(\mathbf{V}_p\) is extracted and checked for positive-definiteness (all eigenvalues \(> 10^{-10}\); projected to the nearest PD matrix if needed). But \(\mathbf{V}_p\) treats households as independent, which understates uncertainty under a clustered survey design. The draws therefore use a FSU-clustered robust (CR1) sandwich covariance instead:
where \(\mathbf{s}_c\) sums the household score contributions within primary sampling unit (FSU) \(c\). This carries the complex-survey clustering into every draw, so a single set of draws yields design-consistent intervals — there is no separate survey-variance pass and no post-hoc noise injection.
7.2 Coefficient Draws
Draw \(M = 200\) coefficient vectors from the clustered sandwich (via
mvnfast::rmvn()); if it cannot be formed, fall back to
\(\mathbf{V}_p\) with smoothing-parameter uncertainty (unconditional = TRUE):
Each of the seven models is drawn independently; measures that combine models (e.g. \(mr = mp\times mm\)) are formed draw-by-draw so their intervals are coherent.
7.3 Predictions and Back-Transform
Unlike the food-consumption two-part model, each Shannon model is a single Gaussian response on the logit scale, so there is no participation/quantity split. Predictions are formed by matrix multiplication on the standardized population, chunked over rows for memory:
The normalized index \(\tilde{H}^{(m)}\in(0,1)\) is the reported measure \(m\) (adjusted) or \(mca\) (cereal-adjusted). For the plain-Shannon measure it is rescaled to the raw entropy scale, \(mp = \tilde{H}^{(m)}\times\log K\); the MAR measure \(mm\) is \(\operatorname{plogis}\) of the \(z_{\text{mar}}\) predictor.
7.4 Aggregation and Summary
For each draw the household predictions are aggregated with survey weights to a group × decile mean (and an Overall row). The \(M\) resulting values form the sampling distribution of each cell, from which:
- Point estimate: mean across draws.
- 95% credible interval: 2.5th and 97.5th percentiles of the draws.
- SE: standard deviation across draws.
The descriptive excess-cereal share ecs is not modeled; it is a survey-weighted
mean (group-specific in the standardized panel) with a normal-approximation interval.
8. R Code Reference
8.1 Index Construction
The Shannon Diversity Index is constructed in R using tidyverse and data.table operations. The key function analysis_shannon_food() is sourced from model_food_AFE.R:
# Pseudocode for index construction
analysis_shannon_food <- function(data) {
# Pivot from wide (food categories) to long format
data_long <- pivot_longer(data, cols = food_cols,
names_to = "food", values_to = "intake_gm")
# Merge with requirements
data_long <- merge(data_long, requirements_df, by = "food")
# Compute per-AFE intake
data_long$intake_afe <- data_long$intake_gm / data_long$afe_size
# Cap at requirement
data_long$capped <- pmin(data_long$intake_afe, data_long$requirement)
# Summarize by household
by_hh <- data_long[, .(total_capped = sum(capped)), by = household_id]
data_long <- merge(data_long, by_hh, by = "household_id")
# Compute shares
data_long$share <- data_long$capped / data_long$total_capped
# Shannon entropy
data_long$h_component <- -data_long$share * log(data_long$share + 1e-10)
shannon_h <- data_long[, .(H = sum(h_component)), by = household_id]
# Adequacy adjustment
data_long$adequacy <- pmin(data_long$intake_afe / data_long$requirement, 1)
adequacy_a <- data_long[, .(A = mean(adequacy)), by = household_id]
# Cereal adjustment (gram-based)
cereal_data <- data_long[food == "cereals"]
cereal_adj <- pmax(cereal_data$share - cereal_req_share, 0)
cereal_penalty <- exp(-3 * cereal_adj)
# Combine
result <- merge(shannon_h, adequacy_a, by = "household_id")
result$cereal_penalty <- cereal_penalty
result$H_adj <- result$H * result$A * result$cereal_penalty
return(result)
}
8.2 Model Estimation
The GAM is estimated using mgcv::bam() for efficiency:
# Normalize and logit-transform the Shannon index
K <- length(food_vars) # number of food groups (9)
eps <- 1e-6
data <- data1 %>%
mutate(
Hnorm = shannon_req_A / log(K),
Hnorm01 = pmin(pmax(Hnorm, eps), 1 - eps),
z = qlogis(Hnorm01)
)
# GAM formula (shared with the food-consumption model, seasonal ON)
quant <- z ~ sector + child + female_headed + social + rel +
s(log_mpce_real_afe, k = 10) +
s(state_code, bs = "re") +
s(log_mpce_real_afe, state_code, bs = "fs", k = 5, m = 1) +
s(log_mpce_real_afe, by = child_o, k = 5) +
s(log_mpce_real_afe, by = female_headed_o, k = 5) +
s(log_mpce_real_afe, by = social_o, k = 5) +
s(log_mpce_real_afe, by = rel_o, k = 5) +
s(nss_region, bs = "re") +
s(reg_sector, bs = "re") +
seasonal + s(log_mpce_real_afe, by = seasonal_o, k = 5)
# Fit using bam() for large-dataset efficiency
model_shannon_food <- mgcv::bam(
quant,
data = data,
weights = data$w_pc,
method = "fREML",
discrete = TRUE,
gamma = 1.4,
gc.level = 2,
select = TRUE
)
# Estimate for both survey rounds and save
models <- list(
HCES2011_model = analysis_shannon_food("HCES2011"),
HCES2023_model = analysis_shannon_food("HCES2023")
)
save(models, file = file.path(folder, "Shannon_Diversity_food_model.RData"))
8.3 Prediction Data Generation
Post-estimation is handled by post_estimation_shannon.R and driven by
produce_dashboard_shannon_js.R. The entry point
run_postestimation_shannon() draws coefficients from the FSU-clustered sandwich,
standardizes each covariate by g-computation, and summarizes across draws — separately for
the ratio and gram bases:
run_postestimation_shannon <- function(models,
covariates = c("sector","social","rel","child",
"female_headed","state_code","nss_region"),
n_groups = 10,
income_var = "mpce_real_2023_afe", # 2023-rupee AFE income deciles
B = 200, # posterior draws
robust = TRUE, cluster_var = "psu", # FSU-clustered CR1 sandwich
basis = c("ratio","gram")) {
# gram basis aliases the gram models + swaps in the gram excess-cereal column
if (basis == "gram") {
models$model_shannon_food <- models$model_shannon_gram
models$model_shannon_plain <- models$model_shannon_gram_plain
models$model_shannon_cereal_adj <- models$model_shannon_gram_cereal_adj
models$data$cereal_share_excess <- models$data$cereal_share_excess_gram
}
logK <- log(models$K)
betas <- build_betas_shannon(models, B, seed, robust, cluster_var) # clustered draws
list(
unadjusted = unadjusted_breakdowns_shannon(models, betas, logK, ...), # observed composition
adjusted = lapply(covariates, function(v) # g-computation
standardize_covariate_shannon(models, betas, logK, v, ...)))
}
# produce_dashboard_shannon_js.R writes one file per basis:
# ratio -> data_shannon_food_new.js (const DATA_RATIO)
# gram -> data_shannon_food_gram_new.js (const DATA)
Measures are formed draw-by-draw inside measure_mats():
m = plogis(ηz), mp = plogis(ηzp) × log K,
mm = plogis(ηzm), mr = mp × mm, and the modeled
mca = plogis(ηzc); the descriptive ecs is a
survey-weighted mean. There is no svydesign pass and no noise injection
— the survey clustering is carried entirely by the sandwich covariance of the draws.
9. Summary of Model Assumptions
The methodology rests on several key assumptions:
- Smooth Engel Curves: We assume the relationship between log expenditure and dietary diversity is smooth and continuous (penalized spline assumption).
- Normal Posterior Approximation: The posterior distribution of model coefficients is assumed multivariate normal, justified by large-sample Bayesian asymptotics.
- Additivity of Uncertainty: Model and sampling uncertainty are combined additively (in log space), assuming they are approximately independent.
- Logit Transformation Adequacy: The logit transformation correctly maps the bounded Shannon index to the real line for Gaussian regression.
- Exchangeability: Within survey rounds, households are treated as exchangeable conditional on covariates, justifying the random effects specification.
References
Last updated: February 2026