*! version 4.4 2026-04-25

Title

medage -- Calculate linear interpolated median age from 5-year age group data.

Syntax

medage varname [if] [in] , ageid(varname) [options]

ageid(varname) Required; numeric ID for 5-year age groups (e.g., 1=0-4, 2=5-9).

saving(filename) Save results to a new Stata dataset (Batch Mode).

by(varlist) Variables defining groups for Batch Mode.

replace Overwrite existing file in Batch Mode.

The command is byable(recall) for interactive use.

Description

medage is a professional demographic tool designed to estimate the median age from
population data aggregated into 5-year age intervals (e.g., 0-4, 5-9, 10-14, ..., 95+).
It assumes that the distribution of individuals across single years of age within
such intervals is uniform enough that linear interpolation across the interval provides
a statistically reliable approximation of the true population median.

Data Structure and Pre-processing

medage requires the dataset to be collapsed to the unit of analysis. For each
unique combination of variables in by() (Batch Mode) or for the current selection
(Interactive Mode), there must be exactly one observation per age group.

Note on Validation: To ensure demographic accuracy, medage performs a
structural check before calculation. If multiple observations are found for the
same ageid within a group, the command will issue error 459 and exit.

If the data contains multiple records per ageid (e.g., population by province when
calculating a national or regional median), you must collapse the data first:

. collapse (sum) population, by(region scenario year ageid)

. medage population, ageid(ageid) by(region scenario year) saving(results.dta)

Modes of Operation

1. Interactive Mode: Used for quick analysis. When saving() is not
specified, the command displays results in the Results window. Supports by:.

2. Batch Mode (Vectorized): Optimized for large-scale projections. Processes
every group defined in by() and saves results to a new .dta file.

Methods and Formulas

Derived from The Methods and Materials of Demography (Siegel and Swanson):

Median = L + [ ( (N/2) - CF ) / f ] * 5

where:

L = Lower limit of the median interval

N = Total population

CF = Cumulative frequency before the median interval

f = Frequency (population) within the median interval

Examples

Quick interactive check for a specific group (ensure sorted by group):

. bysort ctrystr scenario: medage population, ageid(ageid)

Process all countries and scenarios, saving to a results file:

. medage population, ageid(ageid) by(ctrystr scenario) saving(proj_results.dta) replace

Stored results

medage stores the following in r():

Scalars

r(median) interpolated median age

r(N) total population analyzed

Author

Anne Fengyan Shi, Pew Research Center

ashi@pewresearch.org