Internals
Everything the API reference does not list, including names without a leading underscore. None of it carries a compatibility guarantee.
The two filters partition the module and checkdocs = :all fails the build on any docstring that falls through both, so a name added to one list and not removed from the other cannot slip past CI.
NHANES._all_cycles — Method
All cycles to search by default (regular years + pre-pandemic).
NHANES._apply_labels! — Method
_apply_labels!(df::DataFrames.DataFrame, table::AbstractString)Apply value labels to the categorical columns of a DataFrame. Continuous columns keep their numeric values. Uses cached labels, no redundant downloads.
NHANES._build_codebook_from_data — Method
_build_codebook_from_data(df::DataFrames.DataFrame, variable::Symbol, entry) -> DataFrameBuild codebook DataFrame with counts computed from actual data.
Emits one row per row CDC publishes, in order. Values matching no published code are appended so the counts account for every observation.
NHANES._code_sort_key — Method
_code_sort_key(code::AbstractString)Sort key placing numeric codes in numeric order ahead of non-numeric ones.
NHANES._directory — Method
Directory part of a URL path, including the trailing slash.
NHANES._dxa_table_name — Method
Build DXA table name.
NHANES._dxa_url — Method
Build URL for DXA data file.
NHANES._fetch_pages — Method
_fetch_pages(f, components, cycles) -> Vector{Tuple}Apply f(component, cycle) to every pair, keeping up to SEARCH_CONCURRENCY fetches in flight, and return (component, cycle, result) triples in components by cycles order however the fetches interleave. Pairs CDC does not publish are dropped, as in _skip_missing. A failure surfaces with its original type once the fetches in flight settle, and stops the remaining pairs from being fetched.
NHANES._format_code — Method
Format numeric code for label lookup.
NHANES._get_cached_variablelist — Method
_get_cached_variablelist(component::Symbol, year::Union{Int,Symbol};
force::Bool=false) -> Vector{Dict}Get variable list for a component/year, using cache if available.
NHANES._get_table_labels — Method
_get_table_labels(table::AbstractString; force::Bool=false) -> DictGet the parsed value table for every variable in a data table, using cache if available. Returns Dict mapping variable name -> value table, as built by _parse_all_value_labels.
NHANES._historical_cache_path — Method
_historical_cache_path(survey::Symbol, name::AbstractString, extension::AbstractString) -> StringCache file path for a historical data file, keeping the extension CDC publishes it under.
Throws
ArgumentError: If the name is not a plain identifier, or the extension is not one CDC publishes data under
NHANES._historical_entry — Method
_historical_entry(survey::Symbol, listing::DataFrames.DataFrame, name::AbstractString) -> NamedTupleFind name in a survey listing, reporting its name, URL and file extension. Lookup ignores case because listing names are always uppercase.
Throws
TableNotFoundError: If the listing holds no file of that name
NHANES._historical_fetch — Method
Path of the cached copy of entry, downloading it first when needed.
NHANES._historical_tables_url — Method
_historical_tables_url(survey::Symbol) -> StringGet URL for historical survey tables list. NHANES I/II use default.aspx, NHANES III uses datafiles.aspx.
NHANES._is_blank — Method
_is_blank(val) -> BoolReport whether a data value is absent. A character column records a blank string where a numeric column records missing.
NHANES._is_historical_data_file — Method
_is_historical_data_file(filename::AbstractString) -> BoolReport whether a linked file holds survey data. Readme files sit next to the data files and share their extension, so they are excluded by name.
NHANES._is_missing_row — Method
_is_missing_row(code::AbstractString) -> BoolReport whether a value table row counts missing observations rather than a code.
NHANES._is_range_row — Method
_is_range_row(code::AbstractString, label::AbstractString) -> BoolReport whether a value table row describes a range of measurements rather than a single code. CDC marks these rows with the description "Range of Values" and a code cell such as "3.2 to 242.6". A character variable's recorded values are also ranges: their code cell repeats the variable description.
NHANES._normalize_path — Method
Collapse . and .. segments in an absolute URL path.
NHANES._parse_all_value_labels — Method
_parse_all_value_labels(html::AbstractString) -> Dict{String,Any}Parse the value table of every variable on a codebook page.
Returns Dict mapping variable name -> Dict with:
"continuous": true when the variable has a range row, so its values are measurements rather than codes"labels": Dict(code_string -> label) for code rows only"rows": every published row, in order, as Dict("code" =>, "label" =>)
NHANES._parse_historical_tables — Method
_parse_historical_tables(html::AbstractString, page_url::AbstractString) -> Vector{Dict}Parse a historical survey listing page. Names are derived from the data file names, which are more reliable than the surrounding description cells. Links are resolved against page_url.
NHANES._parse_tables_from_variablelist — Method
_parse_tables_from_variablelist(html::AbstractString) -> Vector{Dict}Extract unique table information from a variable list page. Each variable on the page names the data file it belongs to.
NHANES._parse_variables_from_codebook — Method
_parse_variables_from_codebook(html::AbstractString) -> Vector{Dict}Extract variable names and labels from a codebook page.
NHANES._require_transport_file — Method
Reject a listing entry that historical_download cannot read.
NHANES._search_components — Method
_search_components(component::Union{Symbol,Nothing}) -> Vector{Symbol}Components a search covers: every component, or just the one requested.
NHANES._search_cycles — Method
_search_cycles(years::Union{Int,AbstractRange,Nothing}) -> Vector{Union{Int,Symbol}}Cycles a search covers, in survey order, dropping years CDC has not published.
NHANES._search_results_to_dataframe — Method
_search_results_to_dataframe(results::Vector) -> DataFrameConvert search results to a DataFrame.
NHANES._skip_missing — Method
_skip_missing(f)Run f, returning nothing when CDC publishes no page for the request. Every other failure propagates, so a network outage or a markup change is not mistaken for an empty result.
NHANES._split_path — Method
Split a URL path from the query string or fragment that follows it.
NHANES._tables_to_dataframe — Method
_tables_to_dataframe(data::Vector) -> DataFrameConvert parsed tables data to a DataFrame. Includes URL column if present in data.
NHANES._translate_column — Method
_translate_column(col, labels_map) -> (Vector{Union{String,Missing}}, Set{String})Replace codes with labels, keeping unlabelled values as strings. Returns the translated column and the codes that had no label.
NHANES._variables_to_dataframe — Method
_variables_to_dataframe(data::Vector) -> DataFrameConvert parsed variables data to a DataFrame.
NHANES._warn_unmatched — Method
_warn_unmatched(table::AbstractString, column::AbstractString, codes)Report codes present in the data that the codebook does not describe.
NHANES.cache_dir — Method
cache_dir() -> StringGet the root cache directory for NHANES data. Creates the directory if it doesn't exist.
NHANES.codebook_url — Method
codebook_url(table::AbstractString) -> StringBuild the URL for a table's codebook/documentation page.
NHANES.cycle_suffix — Method
cycle_suffix(year::Int) -> StringGet the table suffix for a given survey cycle start year.
Throws
ArgumentError: If the year is not a published cycle. 2019 gets a dedicated message pointing at the pre-pandemic cycle:P.
Examples
cycle_suffix(1999) # ""
cycle_suffix(2017) # "_J"NHANES.data_cache_path — Method
data_cache_path(table::AbstractString) -> StringGet the cache file path for a data table.
Throws
ArgumentError: If the table name is not a plain identifier
NHANES.extract_text — Method
extract_text(node) -> StringConcatenate the text content of an HTML node and its descendants.
Text nodes are joined without a separator, so inline markup inside a cell does not introduce whitespace that the rendered page does not have.
NHANES.fetch_file — Method
fetch_file(url::AbstractString, dest::AbstractString; retries::Int=3) -> StringDownload a file from a URL to a destination path.
The transfer goes to a temporary file next to dest and is renamed into place once complete, so a failed download never leaves a truncated file at dest.
Arguments
url::AbstractString: URL to download fromdest::AbstractString: Local path to save the fileretries::Int=3: Maximum number of attempts
Throws
DownloadError: If the download fails
NHANES.fetch_html — Method
fetch_html(url::AbstractString; retries::Int=3) -> StringFetch HTML content from a URL.
Arguments
url::AbstractString: URL to fetchretries::Int=3: Maximum number of attempts
Throws
DownloadError: If the fetch fails
NHANES.http_status — Method
http_status(e) -> Union{Int,Nothing}Get the HTTP status carried by a failure, or nothing when the request failed before a response arrived.
NHANES.is_cached — Method
is_cached(table::AbstractString) -> BoolCheck if a data table is cached.
NHANES.is_metadata_fresh — Method
is_metadata_fresh(path::AbstractString) -> BoolCheck if a metadata cache file exists and is within the TTL.
NHANES.is_transient — Method
is_transient(e) -> BoolReport whether a failure is worth retrying: connection and timeout failures, HTTP 429, and HTTP 5xx. A 4xx response means the resource will not appear on a second attempt.
NHANES.load_metadata — Method
load_metadata(category::AbstractString, key::AbstractString)Load metadata from the cache.
Returns
- Parsed JSON data, or
nothingif not cached or stale
NHANES.metadata_cache_path — Method
metadata_cache_path(category::AbstractString, key::AbstractString) -> StringGet the cache file path for metadata.
Throws
ArgumentError: If the category or key is not a plain identifier
NHANES.normalize_component — Method
normalize_component(comp::Symbol) -> SymbolConvert a component name to its full form. Accepts full names and R-style short names (:DEMO, :DIET, :EXAM, :LAB, :Q), both case-insensitive. Returns: :Demographics, :Dietary, :Examination, :Laboratory, :Questionnaire
NHANES.parse_table_name — Method
parse_table_name(table::AbstractString) -> Tuple{String, String}Parse a table name into its base name and cycle marker.
Returns
Tuple{String, String}: (basename, cyclemarker)- For suffix tables: ("DEMO", "_J")
- For P_ prefix tables: ("BMX", "P_")
- For 1999-2000 tables: ("DEMO", "")
Examples
parse_table_name("DEMO_J") # ("DEMO", "_J")
parse_table_name("ALB_CR_J") # ("ALB_CR", "_J")
parse_table_name("P_BMX") # ("BMX", "P_")
parse_table_name("DEMO") # ("DEMO", "")NHANES.parse_variablelist_html — Method
parse_variablelist_html(html::AbstractString) -> Vector{Dict}Parse a variable list HTML page.
Returns
Vector{Dict}: One entry per variable, withname,description,tableandtable_descriptionkeys
NHANES.resolve_url — Method
resolve_url(base::AbstractString, href::AbstractString) -> StringResolve a link against the absolute URL of the page it appeared on.
Absolute links are returned unchanged and protocol-relative links take the scheme of base. Everything else is joined onto base, with . and .. segments collapsed and .. stopping at the root.
Throws
ArgumentError: Ifbaseis not an absolute URL
Examples
resolve_url(
"https://wwwn.cdc.gov/nchs/nhanes/nhanes3/datafiles.aspx",
"../../data/nhanes3/1a/adult.dat",
)
# "https://wwwn.cdc.gov/nchs/data/nhanes3/1a/adult.dat"NHANES.save_metadata — Method
save_metadata(category::AbstractString, key::AbstractString, data) -> StringSave metadata to the cache as JSON.
NHANES.suffix_to_year — Method
suffix_to_year(suffix::AbstractString) -> IntConvert a table suffix to the survey cycle start year. The leading underscore is optional.
Examples
suffix_to_year("_J") # 2017
suffix_to_year("B") # 2001
suffix_to_year("") # 1999NHANES.survey_years — Method
survey_years() -> Vector{Int}List the start years of every published survey cycle, in ascending order.
NHANES.table_rows — Method
table_rows(html::AbstractString) -> Vector{Vector{String}}Extract the text of the td cells of every table row on a page, one entry per row. Header rows, which hold th cells, come back empty.
Returns
Vector{Vector{String}}: Cell text per row, in document order
NHANES.table_url — Method
table_url(table::AbstractString) -> StringBuild the download URL for an NHANES data table.
Examples
table_url("DEMO_J")
# "https://wwwn.cdc.gov/Nchs/Data/Nhanes/Public/2017/DataFiles/DEMO_J.xpt"
table_url("P_BMX")
# "https://wwwn.cdc.gov/Nchs/Data/Nhanes/Public/2017/DataFiles/P_BMX.xpt"NHANES.validate_name — Method
validate_name(name::AbstractString, kind::AbstractString) -> StringCheck that a name cannot escape the directory or URL path it is joined into. Returns the name unchanged.
Throws
ArgumentError: If the name contains anything but letters, digits and underscores
NHANES.variablelist_url — Method
variablelist_url(component::Symbol, year::Union{Int,Symbol}) -> StringBuild the URL for the variable list page.
NHANES.with_cache_dir — Method
with_cache_dir(f, dir::AbstractString)Run f with the cache root redirected to dir, restoring the previous root afterwards.
NHANES.with_retries — Method
with_retries(f, url, action, retries; backoff = RETRY_BACKOFF_SECONDS)Run f, retrying transient failures with exponential backoff.
Arguments
f: Zero-argument function performing the requesturl::AbstractString: URL being requested, reported in errorsaction::AbstractString: Whatfis doing, reported in errorsretries::Int: Maximum number of attemptsbackoff::Real: Delay in seconds before the first retry
Throws
DownloadError: If the request fails permanently or runs out of attempts
NHANES.CACHE_ROOT_OVERRIDE — Constant
Cache root to use instead of the Scratch.jl space, or nothing for the default. Tests redirect the cache here so they never touch a real download cache; see with_cache_dir.
NHANES.COMPONENTS — Constant
Valid NHANES data components for continuous NHANES (1999-present).
NHANES.COMPONENT_ALIASES — Constant
Mapping from R-style short component names to full names.
NHANES.COMPONENT_LOOKUP — Constant
Mapping from lowercased component spellings, both full names and R-style aliases, to full names. Backs case-insensitive lookup.
NHANES.DXA_YEARS — Constant
Valid years for DXA data.
NHANES.HISTORICAL_DATA_EXTENSIONS — Constant
File extensions of the historical data files CDC publishes.
NHANES.HISTORICAL_SURVEYS — Constant
Historical survey identifiers.
NHANES.METADATA_TTL_DAYS — Constant
Number of days before metadata cache is considered stale.
NHANES.MISSING_CODE — Constant
Code cell CDC uses for the missing row of a numeric value table.
NHANES.MISSING_CODES — Constant
Code cells CDC uses for the missing row, numeric and character.
NHANES.PREPANDEMIC_CYCLE — Constant
Pre-pandemic cycle identifier (2017-March 2020). Tables use P_ prefix instead of suffix.
NHANES.RANGE_DESCRIPTION — Constant
Description CDC uses for the row covering a variable's measured range.
NHANES.RETRY_BACKOFF_SECONDS — Constant
Base delay in seconds before a retry, doubled on each further attempt.
NHANES.SAFE_NAME — Constant
Names that are safe to embed in a cache path or a CDC URL.
NHANES.SEARCH_CONCURRENCY — Constant
Number of CDC page fetches allowed in flight at once. Six matches the per-host connection limit browsers use, so a search asks no more of wwwn.cdc.gov than loading the same pages in a browser would, and measured throughput stops improving beyond it.
NHANES.SUFFIX_TO_YEAR — Constant
Mapping of table suffixes back to survey cycle start years.
NHANES.SURVEY_CYCLES — Constant
Mapping of survey cycle start years to table suffixes.
Continuous NHANES uses letter suffixes starting from 1999-2000:
- 1999-2000: no suffix (or sometimes _A in older tables)
- 2001-2002: _B
- 2003-2004: _C
- etc.
The 2019-2020 cycle was cut short by COVID-19 and never published on its own. Its data was released as part of the 2017-March 2020 pre-pandemic files, and CDC skipped the letter _K, so 2021-2023 uses _L.