| Title: | Tidy Access to Mongolian Official Statistics and Metadata |
|---|---|
| Description: | A 'tidyverse'-friendly client for the public statistical services of the National Statistics Office of Mongolia <https://data.1212.mn/>. Discover tables and their dimensions, and fetch statistical data as 'tibble' data frames with English or Mongolian labels. Periods are reported by their labels and can be selected in any of the office's period formats, tables that have moved within the catalogue are found automatically, and large requests are split to stay within the server's limits. Source provenance and raw observation symbols support reproducible exports. Experimental clients provide access to the public data and metadata portals, including official definitions, collection forms, classifications, and reviewed indicator queries. Maps and joins by statistical code are provided by the companion package 'mongolmaps'. |
| Authors: | Temuulen Enebish [aut, cre, cph], National Statistics Office of Mongolia [cph] (Bundled statistical extracts; see inst/COPYRIGHTS) |
| Maintainer: | Temuulen Enebish <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.0 |
| Built: | 2026-10-31 18:54:38 UTC |
| Source: | https://github.com/cran/mongolstats |
Convert a query to a PXWeb body
as_px_query(x, lang = .px_lang())as_px_query(x, lang = .px_lang())
x |
An |
lang |
PX language: "en" or "mn" (defaults to current option). |
A list suitable to send as JSON body to PXWeb.
q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023")) body <- as_px_query(q)q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023")) body <- as_px_query(q)
mn_boundaries() was deprecated in mongolstats 0.3.0. Use the mongolmaps
package instead: mongolmaps::mn_admin() and its shortcuts
(mn_country(), mn_aimags(), mn_soums(), ...) ship boundaries that
carry NSO codes, need no download, and join to NSO tables by code with
mongolmaps::mn_join().
mn_boundaries() downloads boundaries for ADM0/ADM1/ADM2 from the
geoBoundaries API and returns an sf object (the sf package must be
installed). Results are cached in memory for the session.
mn_boundaries(level = c("ADM0", "ADM1", "ADM2"), refresh = FALSE)mn_boundaries(level = c("ADM0", "ADM1", "ADM2"), refresh = FALSE)
level |
One of "ADM0", "ADM1", "ADM2". |
refresh |
If TRUE, bypass the session cache and download again. |
An sf object with polygons for the requested level. Failed
downloads raise an error of class mongolstats_http_error.
aimags <- mn_boundaries("ADM1") # -> if (rlang::is_installed("mongolmaps")) { aimags <- mongolmaps::mn_aimags() }aimags <- mn_boundaries("ADM1") # -> if (rlang::is_installed("mongolmaps")) { aimags <- mongolmaps::mn_aimags() }
mn_boundaries_normalize() was deprecated in mongolstats 0.3.0 together
with mn_boundaries(). To match place names in any spelling, use
mongolmaps::mn_match().
Adds a name_std column to an sf boundary object by transliterating,
lowercasing, and stripping special characters from place names.
mn_boundaries_normalize(g, name_col = "shapeName")mn_boundaries_normalize(g, name_col = "shapeName")
g |
sf object from |
name_col |
Column with English names (default 'shapeName'). |
An sf object with an additional name_std column.
aimags <- mn_boundaries_normalize(mn_boundaries("ADM1")) # -> if (rlang::is_installed("mongolmaps")) { mongolmaps::mn_match(c("Khuvsgul", "Hovsgol"), to = "name_en") }aimags <- mn_boundaries_normalize(mn_boundaries("ADM1")) # -> if (rlang::is_installed("mongolmaps")) { mongolmaps::mn_match(c("Khuvsgul", "Hovsgol"), to = "name_en") }
mn_boundary_keys() was deprecated in mongolstats 0.3.0. Use
mongolmaps::mn_codes(), which lists every administrative unit with its
NSO code, ISO 3166-2 code, P-code and names.
Returns a lightweight tibble of key columns from the geoBoundaries data, including normalized names, without the full geometry.
mn_boundary_keys(level = "ADM1")mn_boundary_keys(level = "ADM1")
level |
Boundary level. |
A tibble with key columns from GeoBoundaries and normalized names.
keys <- mn_boundary_keys("ADM1") # -> if (rlang::is_installed("mongolmaps")) { keys <- mongolmaps::mn_codes("aimag") }keys <- mn_boundary_keys("ADM1") # -> if (rlang::is_installed("mongolmaps")) { keys <- mongolmaps::mn_codes("aimag") }
mn_fuzzy_join_by_name() was deprecated in mongolstats 0.3.0. Use
mongolmaps::mn_join(), which knows the common spellings of every aimag
and soum and reports each fuzzy match it makes.
Performs a fuzzy string-distance join between a data frame and geoBoundaries polygons.
mn_fuzzy_join_by_name( data, name_col, level = "ADM1", boundaries = NULL, max_distance = 2, method = c("osa", "lv", "jw", "dl") )mn_fuzzy_join_by_name( data, name_col, level = "ADM1", boundaries = NULL, max_distance = 2, method = c("osa", "lv", "jw", "dl") )
data |
Data frame with a name column. |
name_col |
Column in |
level |
Boundary level. |
boundaries |
Optional pre-fetched boundaries. |
max_distance |
Maximum string distance for a match (default 2). For
the edit distances ( |
method |
Distance method passed to |
sf with best fuzzy matches joined. Data rows with no boundary
within max_distance are dropped with a warning (class
mongolstats_unmatched_names) naming them; rows with a missing name
are dropped silently.
pop_data <- data.frame(aimag = c("Ulanbatar", "Darhan"), pop = c(1500000, 100000)) sf_joined <- mn_fuzzy_join_by_name(pop_data, "aimag", level = "ADM1") # -> if (rlang::is_installed("mongolmaps")) { sf_joined <- mongolmaps::mn_join(pop_data, by = "aimag", level = "aimag") }pop_data <- data.frame(aimag = c("Ulanbatar", "Darhan"), pop = c(1500000, 100000)) sf_joined <- mn_fuzzy_join_by_name(pop_data, "aimag", level = "ADM1") # -> if (rlang::is_installed("mongolmaps")) { sf_joined <- mongolmaps::mn_join(pop_data, by = "aimag", level = "aimag") }
mn_join_by_name() was deprecated in mongolstats 0.3.0. Use
mongolmaps::mn_join(), which joins by NSO code or by name in any
spelling, drops national and regional totals, and takes Ulaanbaatar's
figures from region code "5" when a table leaves code "511" empty.
Performs an exact join between a data frame and geoBoundaries polygons using normalized place names.
mn_join_by_name(data, name_col, level = "ADM1", boundaries = NULL)mn_join_by_name(data, name_col, level = "ADM1", boundaries = NULL)
data |
Data frame with a name column. |
name_col |
Column in |
level |
Boundary level, passed to |
boundaries |
Optional pre-fetched boundaries. |
An sf object with joined data. Data rows whose name matches no
boundary are dropped with a warning (class
mongolstats_unmatched_names) naming them.
pop_data <- data.frame(aimag = c("Ulaanbaatar", "Darkhan-Uul"), pop = c(1500000, 100000)) sf_joined <- mn_join_by_name(pop_data, "aimag", level = "ADM1") # -> if (rlang::is_installed("mongolmaps")) { sf_joined <- mongolmaps::mn_join(pop_data, by = "aimag", level = "aimag") }pop_data <- data.frame(aimag = c("Ulaanbaatar", "Darkhan-Uul"), pop = c(1500000, 100000)) sf_joined <- mn_join_by_name(pop_data, "aimag", level = "ADM1") # -> if (rlang::is_installed("mongolmaps")) { sf_joined <- mongolmaps::mn_join(pop_data, by = "aimag", level = "aimag") }
Retrieves the configuration advertised by the current PXWeb base URL and
language. Successful results are cached for this R session. A failed refresh
returns the previous configuration with status = "stale"; without a cache,
conservative defaults are returned. Offline mode never makes a request.
nso_api_config(refresh = FALSE)nso_api_config(refresh = FALSE)
refresh |
Logical. Bypass the session cache and request the configuration again. Has no network effect in offline mode. |
maxCells limits cells in a data-query result. maxValues limits values
returned per variable in table metadata; it is not a selection limit for
data queries. maxCalls and timeWindow describe the server's advertised
request allowance. The package separately applies at least one second
between NSO request attempts, including retries. Calls on one computer
coordinate through mongolstats.rate_limit_dir; computers sharing a public
IP address require additional coordination by the caller.
A list with numeric maxCells, maxValues, maxCalls, and
timeWindow (seconds), plus origin ("server", "cache", or
"defaults"), status ("available", "partial", "stale",
"offline", or "unavailable"), base_url, and lang. Invalid or missing
individual limits are replaced by conservative defaults and marked partial.
PxWeb configuration manual, API feature, pages 74–75.
old <- nso_options(mongolstats.offline = TRUE) nso_api_config() options(old)old <- nso_options(mongolstats.offline = TRUE) nso_api_config() options(old)
Clear cached entries
nso_cache_clear()nso_cache_clear()
Invisibly, TRUE.
nso_cache_clear()nso_cache_clear()
Disable caching
nso_cache_disable()nso_cache_disable()
Invisibly, TRUE.
nso_cache_disable()nso_cache_disable()
Caches PXWeb catalogue listings and table metadata (codebooks) on disk to
speed up repeated calls, including across R sessions. Entries are keyed by
the PXWeb base URL, database, and language, so changing
mongolstats.px_base_url or mongolstats.px_db never returns another
server's metadata. Data fetched with nso_data() is not cached.
The default cache uses tools::R_user_dir(), is limited to 10 MiB, and
removes entries older than seven days. Existing caches in the former
rappdirs location are not read or deleted automatically.
nso_cache_enable(dir = NULL, ttl = 7 * 24 * 60 * 60)nso_cache_enable(dir = NULL, ttl = 7 * 24 * 60 * 60)
dir |
Directory for cache; defaults to user cache dir. |
ttl |
Time-to-live in seconds for cached entries. Defaults to seven
days. |
Cache directory path (invisibly).
# Enable caching in a temporary directory (for demo purposes) cache_dir <- tempfile("mongolstats-cache-") nso_cache_enable(dir = cache_dir) # Check status nso_cache_status() # Disable when done nso_cache_disable() unlink(cache_dir, recursive = TRUE)# Enable caching in a temporary directory (for demo purposes) cache_dir <- tempfile("mongolstats-cache-") nso_cache_enable(dir = cache_dir) # Check status nso_cache_status() # Disable when done nso_cache_disable() unlink(cache_dir, recursive = TRUE)
Report current cache configuration and basic stats.
nso_cache_status()nso_cache_status()
A list with enabled, dir, and has_cache.
nso_cache_status()nso_cache_status()
Reports index coverage and distinct table counts separately from cross-listed catalogue entries. A bundled index with an unknown build time is identified explicitly. Live keyword searches describe a search window rather than a complete catalogue rebuild.
nso_catalogue_status()nso_catalogue_status()
A one-row tibble with service identity, entries, distinct tables,
coverage, indexed_at, and the source of the index.
# Inspect the bundled or session catalogue without a network request. nso_catalogue_status()# Inspect the bundled or session catalogue without a network request. nso_catalogue_status()
These optional checks report concerns without altering observations or interpreting undocumented source symbols. Supply observation keys, units, expected periods, and geographic levels explicitly. Different measures and populations require substantive review even when these checks find no issue.
nso_check_data( data, keys = NULL, unit = NULL, period = NULL, expected_periods = NULL, geography_level = NULL )nso_check_data( data, keys = NULL, unit = NULL, period = NULL, expected_periods = NULL, geography_level = NULL )
data |
A data frame, preferably an original fetched result. |
keys |
Character vector of columns identifying an observation. |
unit |
Optional column containing units. |
period |
Optional column containing period labels. |
expected_periods |
Optional expected labels, compared literally. |
geography_level |
Optional column containing explicit geographic levels. |
A tibble with check, severity, message, and n (affected rows
or values). An empty tibble means none of the requested checks found an
issue; it does not establish semantic comparability.
# Constructed records contain a duplicate key and an unresolved symbol. observations <- data.frame( period = c("2023", "2023"), value = c(12, NA_real_), value_raw = c("12", ".."), value_status = c("observed", "symbol") ) nso_check_data( observations, keys = "period", period = "period", expected_periods = c("2023", "2024") )# Constructed records contain a duplicate key and an unresolved symbol. observations <- data.frame( period = c("2023", "2023"), value = c(12, NA_real_), value_raw = c("12", ".."), value_status = c("observed", "symbol") ) nso_check_data( observations, keys = "period", period = "period", expected_periods = c("2023", "2024") )
Citations describe the source rather than the software license. NSO public statistics are subject to the source's terms of use and attribution rules; other catalog records may have different access and reuse conditions.
nso_citation(x)nso_citation(x)
x |
A fetched result or provenance manifest. |
A character vector of citations, one per source record.
https://www.nso.mn/en/terms_of_use
# No citation is invented for data without source records. observations <- data.frame(value = c(12, 15)) nso_citation(observations)# No citation is invented for data without source records. observations <- data.frame(value = c(12, 15)) nso_citation(observations)
Retrieve a versioned metadata classification codebook
nso_classification(id, include_raw = FALSE)nso_classification(id, include_raw = FALSE)
id |
Numeric metadata classification identifier. |
include_raw |
Retain the raw response in the |
A tibble with character codes, definitions, parent codes, source,
and version. Attributes contain the typed metadata, quality_flags,
and completeness: "empty", "incomplete", or "unverified".
Nonempty responses do not establish completeness. No cross-service
geographic equivalence or administrative vintage is inferred.
codes <- nso_classification(3446) codes attr(codes, "completeness") attr(codes, "metadata")$versioncodes <- nso_classification(3446) codes attr(codes, "completeness") attr(codes, "metadata")$version
Fetch statistical data for a table (PXWeb)
nso_data( tbl_id, selections, labels = c("none", "en", "mn", "both"), value_name = getOption("mongolstats.value_name", "value"), include_raw = getOption("mongolstats.attach_raw", FALSE) )nso_data( tbl_id, selections, labels = c("none", "en", "mn", "both"), value_name = getOption("mongolstats.value_name", "value"), include_raw = getOption("mongolstats.attach_raw", FALSE) )
tbl_id |
Table identifier (e.g., "DT_NSO_0300_001V2"). |
selections |
Named list mapping variable labels (e.g., Year, Sex) to desired codes or labels. |
labels |
Label handling: "none" (codes only), "en", "mn", or "both".
"code" is accepted as an alias for "none" (matching |
value_name |
Name of the numeric value column in the result (default: "value"). |
include_raw |
If TRUE, attach the raw PX payload as attribute |
A tibble with one column per dimension and a numeric value column.
NSO codes periods by position: in every table, code "0" is the latest
period, so a period's code changes whenever a new one is published. The
time dimension (years, quarters, months or dates) is therefore always
returned by its label, such as "2024" or "2024-03", whatever labels
is; nso_period_date() converts these labels to dates. Other dimensions
are returned as codes unless labels asks for labels.
Select periods by label (Year = "2024"), with nso_period_seq()
(Month = nso_period_seq("202401", "202412", by = "M")), or with
nso_latest_periods(). Periods match whatever format the table uses, so
"202403", "2024-03" and "2024M3" select the same month.
Larger selections are split into requests under the configured cell limit.
nso_api_config() discovers server limits; cached limits and
mongolstats.max_cells are respected. The package coordinates NSO request
attempts on the same computer, including workers, at a conservative rate.
# Population of Mongolia by sex in the two latest years pop <- nso_data( tbl_id = "DT_NSO_0300_001V2", selections = list( Sex = c("Male", "Female"), Age = "Total", Year = nso_latest_periods("DT_NSO_0300_001V2", n = 2) ), labels = "en" ) pop# Population of Mongolia by sex in the two latest years pop <- nso_data( tbl_id = "DT_NSO_0300_001V2", selections = list( Sex = c("Male", "Female"), Age = "Total", Year = nso_latest_periods("DT_NSO_0300_001V2", n = 2) ), labels = "en" ) pop
Returns codes and optional labels for a specific dimension.
nso_dim_values(tbl_id, dim, labels = c("code", "en", "mn", "both"))nso_dim_values(tbl_id, dim, labels = c("code", "en", "mn", "both"))
tbl_id |
Table identifier (e.g., "DT_NSO_0300_001V2"). |
dim |
Dimension name or code (case-insensitive; exact match preferred). |
labels |
One of "code", "en", "mn", or "both" to control returned label columns. "none" is accepted as an alias for "code". |
A tibble with at least code; may include label_en and/or label_mn.
In offline mode (see nso_offline_enable()) an empty tibble is
returned; failed requests raise an error of class
mongolstats_http_error.
values <- nso_dim_values("DT_NSO_0300_001V2", "Year") head(values)values <- nso_dim_values("DT_NSO_0300_001V2", "Year") head(values)
Returns one row per dimension with basic metadata.
nso_dims(tbl_id)nso_dims(tbl_id)
tbl_id |
Table identifier (e.g., "DT_NSO_0300_001V2"). |
A tibble with columns: dim (display name), code (dimension code),
is_time (whether it is the table's time dimension; see
nso_table_periods()), and n_values (number of values for the
dimension).
In offline mode (see nso_offline_enable()) an empty tibble is
returned; failed requests raise an error of class
mongolstats_http_error.
dims <- nso_dims("DT_NSO_0300_001V2") dimsdims <- nso_dims("DT_NSO_0300_001V2") dims
Executes an nso_query and returns a tidy tibble with one column per
dimension and a numeric value column. Use labels to add _en/_mn
columns for each dimension.
nso_fetch( x, labels = c("code", "en", "mn", "both"), value_name = getOption("mongolstats.value_name", "value"), include_raw = getOption("mongolstats.attach_raw", FALSE) )nso_fetch( x, labels = c("code", "en", "mn", "both"), value_name = getOption("mongolstats.value_name", "value"), include_raw = getOption("mongolstats.attach_raw", FALSE) )
x |
An |
labels |
One of "code", "en", "mn", or "both". "none" is accepted
as an alias for "code" (matching |
value_name |
Name of the numeric value column in the result (default: "value"). |
include_raw |
If TRUE, attach the raw PX payload as attribute |
A tibble.
q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023")) data <- nso_fetch(q) head(data)q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023")) data <- nso_fetch(q) head(data)
List collection forms embedded in a metadata database record
nso_forms(database_id, include_raw = FALSE)nso_forms(database_id, include_raw = FALSE)
database_id |
A numeric metadata database identifier. |
include_raw |
Retain the source database response in the result's
|
A tibble of form references with a records list column of typed
embedded records. Records may be partial; use nso_metadata() with
type = "form" to retrieve full details. An empty result means the
database response contained no forms.
forms <- nso_forms(database_id = 526) forms[c("type", "id", "name_mn")] forms$recordsforms <- nso_forms(database_id = 526) forms[c("type", "id", "name_mn")] forms$records
Look up a reviewed concept or a source-qualified portal indicator
nso_indicator(id)nso_indicator(id)
id |
Curated concept, alias, or qualified identifier such as
|
A one-row tibble from nso_indicators(). Unknown or ambiguous IDs
raise an error. A portal match does not supply a reviewed PXWeb template.
nso_indicator("gdp_current")nso_indicator("gdp_current")
Build a PXWeb query from a reviewed statistical concept
nso_indicator_query(id, periods = NULL, geography = NULL)nso_indicator_query(id, periods = NULL, geography = NULL)
id |
Reviewed curated concept or alias; see |
periods |
Optional character vector of period labels, not positional
PXWeb time codes. |
geography |
Optional character vector of source geography codes for
concepts with a geography dimension. |
An nso_query() object ready for nso_fetch(). Construction is
offline; fetching validates selections against current table metadata.
Metadata and caveats can be inspected with nso_indicator().
nso_indicator_query("gdp_current", periods = c("2023", "2024")) nso_indicator_query("resident_population", periods = "2024")nso_indicator_query("gdp_current", periods = c("2023", "2024")) nso_indicator_query("resident_population", periods = "2024")
The curated registry supplies a small set of reviewed PXWeb query templates. Portal discovery is a separate, experimental catalog: an identifier or title shared with PXWeb does not establish statistical equivalence.
nso_indicators(query = NULL, source = c("curated", "portal"), refresh = FALSE)nso_indicators(query = NULL, source = c("curated", "portal"), refresh = FALSE)
query |
Optional literal, case-insensitive text to match across names, identifiers, aliases, and descriptions. |
source |
|
refresh |
Refresh the portal catalog from the service. The curated
registry is bundled and reviewed with package releases, so |
A tibble with source-qualified id, source_id, backend, name,
unit, query availability, and source metadata. Curated rows also contain
definitions, aliases, reviewed selections, caveats and validation dates.
Portal rows retain invalid identifiers with queryable = FALSE, report
quality flags, and preserve the original registry record in a list column.
nso_indicators("GDP") nso_indicators("population")nso_indicators("GDP") nso_indicators("population")
Filters the table catalogue to the tables in a given sector or
sub-sector, as returned by nso_sectors() or nso_subsectors(),
including the tables in its sub-folders.
nso_itms_by_sector(list_id)nso_itms_by_sector(list_id)
list_id |
Path string from |
A tibble of the tables in the sector and its sub-folders.
nso_itms_by_sector("Population, household")nso_itms_by_sector("Population, household")
Returns the labels of the latest periods published in a table, ready to
use in selections. Combine with nso_data() to keep a script on the
newest data without hard-coding years.
nso_latest_periods(tbl_id, n = 1)nso_latest_periods(tbl_id, n = 1)
tbl_id |
Table identifier. |
n |
Number of periods to return. |
A character vector of up to n period labels, oldest first;
empty in offline mode (see nso_offline_enable()).
nso_table_periods() for every period with its date.
nso_latest_periods("DT_NSO_0300_001V2", n = 3) # Fetch the latest year without hard-coding it nso_data( "DT_NSO_0300_001V2", list(Year = nso_latest_periods("DT_NSO_0300_001V2"), Sex = "Total", Age = "Total") )nso_latest_periods("DT_NSO_0300_001V2", n = 3) # Fetch the latest year without hard-coding it nso_data( "DT_NSO_0300_001V2", list(Year = nso_latest_periods("DT_NSO_0300_001V2"), Sex = "Total", Age = "Total") )
These experimental interfaces expose the public catalogue at
https://metadata.nso.mn/. Its numeric identifiers belong to a separate
service from PXWeb table identifiers. An indicator can describe a
questionnaire field rather than a published statistical series.
nso_metadata(type, id, include_raw = FALSE)nso_metadata(type, id, include_raw = FALSE)
type |
Entity type: |
id |
A positive integer identifier in the metadata service. |
include_raw |
Retain the complete parsed response in |
Quality flags identify potential inconsistencies and do not correct the
upstream record. include_raw = TRUE preserves unrecognized fields for
inspection. These endpoints have no published stability guarantee.
The upstream site's certificate chain may be incomplete on some systems;
requests can then fail certificate verification.
An nso_metadata list with source-qualified identity, official
Mongolian text and available English text, dates, integer years,
methodology, access statements, relationships, and quality flags.
$context retains units, value types, collection sources, dissemination
levels, and the responsible department. Its category records preserve
source identifiers and official labels. $date_fields retains original
date and year values, including invalid values, alongside parsed $dates
and $years, even when include_raw = FALSE.
Missing translations remain NA; no translation is generated. Dates
use the calendar date supplied by the service, independent of the local
time zone. Access statements and licence categories do not establish
that the underlying records are publicly downloadable.
field <- nso_metadata("indicator", 12925, include_raw = TRUE) field$quality_flags nso_related(field)field <- nso_metadata("indicator", 12925, include_raw = TRUE) field$quality_flags nso_related(field)
Retrieve official metadata category dictionaries
nso_metadata_dictionary(dictionary)nso_metadata_dictionary(dictionary)
dictionary |
One of |
A tibble of source-qualified category identifiers, character codes,
and official text. The source_url, retrieved_at, and coverage
attributes describe the returned catalogue. A licence or security
category describes metadata and does not establish data availability.
nso_metadata_dictionary("frequency")nso_metadata_dictionary("frequency")
Search or browse the government metadata catalogue
nso_metadata_search( query = "", type = "database", organization = NULL, sector = NULL, page = 1 )nso_metadata_search( query = "", type = "database", organization = NULL, sector = NULL, page = 1 )
query |
Search text. A nonempty query uses the site's public search interface and returns its limited result window, with no pagination. |
type |
Entity type, |
organization |
Numeric organization identifier. Required to browse databases with an empty query. |
sector |
Numeric sector identifier. Filtering applies only to rows
present in the returned response, and rows without the required metadata
are excluded. The |
page |
Positive page number for database browsing. The package sends this value to the service and preserves the reported pagination without assuming that the server honored the requested page. |
A tibble of source-qualified references. Attributes coverage,
exhaustive, pagination, retrieved_at, and unresolved_filter_rows
describe the scope. exhaustive is always FALSE: a returned page,
search window, or response catalogue is not a verified complete inventory.
nso_metadata_search("\u044d\u0440\u04af\u04af\u043b \u043c\u044d\u043d\u0434", type = "all") nso_metadata_search(organization = 1, page = 1) nso_metadata_search(type = "organization")nso_metadata_search("\u044d\u0440\u04af\u04af\u043b \u043c\u044d\u043d\u0434", type = "all") nso_metadata_search(organization = 1, page = 1) nso_metadata_search(type = "organization")
Disable offline mode
nso_offline_disable()nso_offline_disable()
Invisibly, TRUE.
old <- nso_options(mongolstats.offline = TRUE) nso_offline_disable() options(old)old <- nso_options(mongolstats.offline = TRUE) nso_offline_disable() options(old)
When enabled, HTTP requests are prevented and functions that require
the network will raise a clear offline error. Cached metadata can still
be used if already available via nso_cache_enable().
nso_offline_enable()nso_offline_enable()
Invisibly, TRUE.
old <- nso_options(mongolstats.offline = FALSE) # Enable offline mode nso_offline_enable() # Check the option was set getOption("mongolstats.offline") # Restore the original setting options(old)old <- nso_options(mongolstats.offline = FALSE) # Enable offline mode nso_offline_enable() # Check the option was set getOption("mongolstats.offline") # Restore the original setting options(old)
Convenience wrapper around base::options() for mongolstats. Values are
validated before anything is set: for example mongolstats.lang must be
"en" or "mn", and mongolstats.timeout a positive number. Names that
are not mongolstats options are set with a warning, which catches typos.
nso_options(...)nso_options(...)
... |
Named options to set. If empty, returns a named list of current mongolstats options. |
mongolstats.request_interval sets the minimum delay between NSO request
attempts, with a one-second floor. Processes on the same computer coordinate
through mongolstats.rate_limit_dir, which must name the same directory in
each process. This does not coordinate other applications or computers
sharing a public IP address. mongolstats.portal_base_url and
mongolstats.metadata_base_url select the portal and metadata services.
mongolstats.max_cells caps data-query cells; mongolstats.max_values
describes the metadata value-list limit, rather than a data-query limit.
Invisibly, the previous values of the options changed, or a list of current values when called with no arguments.
# Get all current mongolstats options nso_options() # Set an option (save old value for restoration) old <- nso_options(mongolstats.default_labels = "en") # Restore original value options(old)# Get all current mongolstats options nso_options() # Set an option (save old value for restoration) old <- nso_options(mongolstats.default_labels = "en") # Restore original value options(old)
Fetch multiple tables and bind (PXWeb)
nso_package( requests, labels = c("none", "en", "mn", "both"), parallel = getOption("mongolstats.parallel", FALSE), value_name = getOption("mongolstats.value_name", "value"), strict = FALSE )nso_package( requests, labels = c("none", "en", "mn", "both"), parallel = getOption("mongolstats.parallel", FALSE), value_name = getOption("mongolstats.value_name", "value"), strict = FALSE )
requests |
A list of records, each with |
labels |
Label handling as in |
parallel |
If TRUE, fetch tables in parallel with
|
value_name |
Name of the numeric value column in the result (default: "value"). |
strict |
If TRUE, error when any table fails to fetch. If FALSE (default), failed tables are dropped from the result with a warning naming them. |
A tibble combining data from all requested tables, with a tbl_id column
identifying the source table. Tables that failed to fetch are omitted
(with a warning) unless strict = TRUE. nso_provenance() retains a
record per successful table plus explicit failure records;
nso_value_status() identifies each source observation by tbl_id.
reqs <- list( list(tbl_id = "DT_NSO_0300_001V2", selections = list(Year = "2023")) ) combined <- nso_package(reqs)reqs <- list( list(tbl_id = "DT_NSO_0300_001V2", selections = list(Year = "2023")) ) combined <- nso_package(reqs)
NSO tables label periods in several formats, such as "2024",
"2024-03", "2016M3", "2024.03", "2024-I" (first quarter) or
"2026-07-06". nso_period_date() returns the first day of each period,
so results can be sorted, filtered and plotted on a date axis. A trailing
*, which NSO uses to mark preliminary figures, is ignored.
nso_period_date(x)nso_period_date(x)
x |
A character vector of period labels, such as the time column
returned by |
NSO's quarterly tables label quarters "2025-1" to "2025-4". When every
label in x has that form, x is read as quarters; otherwise "2025-4"
is April. Pass a table's whole time column so this can be decided, or see
the frequency column of nso_table_periods().
A Date vector the same length as x holding the first day of
each period. Labels that are not periods, such as "Total", give NA.
nso_table_periods() for the periods available in a table.
nso_period_date(c("2024", "2024-03", "2016M3", "2024-II", "Total"))nso_period_date(c("2024", "2024-03", "2016M3", "2024-II", "Total"))
Builds a run of years (YYYY) or months (YYYYMM) for use in
selections. Selections match these to a table's time labels whatever
format the table uses, so "202403" selects "2024-03", "2024M3" or
"2024.03".
nso_period_seq(start, end, by = c("Y", "M"))nso_period_seq(start, end, by = c("Y", "M"))
start, end
|
Start and end periods as character (YYYY or YYYYMM). |
by |
'Y' for yearly or 'M' for monthly. |
Character vector of periods.
# Generate yearly sequence nso_period_seq("2020", "2024", by = "Y") # Generate monthly sequence nso_period_seq("202401", "202406", by = "M")# Generate yearly sequence nso_period_seq("2020", "2024", by = "Y") # Generate monthly sequence nso_period_seq("202401", "202406", by = "M")
Retrieves the public aggregate endpoint used by data.nso.mn. This service
has an unversioned interface and a separate identifier and geography scheme
from PXWeb. Similar titles or identifiers do not establish equivalence.
nso_portal_data( indicator_id, area = "1", dimension = "code", graph_type = "line", periods = NULL, labels = c("both", "mn", "en", "code"), include_raw = FALSE )nso_portal_data( indicator_id, area = "1", dimension = "code", graph_type = "line", periods = NULL, labels = c("both", "mn", "en", "code"), include_raw = FALSE )
indicator_id |
Portal identifier from |
area |
Portal area parameter, as a nonnegative integer string. The
default |
dimension |
Portal grouping field: |
graph_type |
Portal presentation parameter, such as |
periods |
Optional character vector of exact source period labels.
Filtering takes place after retrieval. A trailing |
labels |
Official label columns to retain: |
include_raw |
Attach the original response as attribute |
The registry supplies source and unit text verbatim when available. It is
descriptive source metadata, not an independently validated semantic
crosswalk. Narrative summaries are not used to construct observations.
Unpadded YYYY-1 to YYYY-4 periods are ambiguous between months and
quarters, so their dates and frequencies remain missing.
A tibble containing backend, source_id, period, date,
frequency, active code dimensions, optional official label columns,
value, value_raw, value_status, and registry unit and source.
Unknown symbols have status "symbol"; no suppression meaning is inferred.
An empty source response returns zero rows; request failures raise errors.
A provenance attribute records the request and optional metadata failures.
nso_portal_data("DT_NSO_0000_4_4", periods = "2024")nso_portal_data("DT_NSO_0000_4_4", periods = "2024")
Lists the portal's public datamart catalog and presentation configuration. A supported developer query contract has not been verified, so this function supplies discovery only. It does not request underlying individual records.
nso_portal_datamarts()nso_portal_datamarts()
A tibble with id, official name, source-reported years, source,
is_visible, a configuration list column, and query_supported = FALSE.
Year ranges and configuration are source text, not verified data coverage.
nso_portal_datamarts()nso_portal_datamarts()
Provenance records the service, source identifier, resolved URL, selections,
retrieval time, source metadata, comments, and a metadata fingerprint.
A batch result contains one record per successful table and explicit failure
records with request indices. Fetch error conditions retain attempted queries
and completed response context; partial tables are never returned as complete.
Attributes can be discarded by transformations; save a sidecar with
nso_write_manifest() before modifying the original result.
nso_provenance(x)nso_provenance(x)
x |
A fetched result, fetch error condition, or a manifest from
|
A list of class nso_manifest with schema_version, records, and
failures. An unannotated result has empty records and failures.
# Provenance is not inferred for an ordinary data frame. observations <- data.frame(value = c(12, 15)) manifest <- nso_provenance(observations) manifest$records manifest$failures# Provenance is not inferred for an ordinary data frame. observations <- data.frame(value = c(12, 15)) manifest <- nso_provenance(observations) manifest$records manifest$failures
Builds a lightweight query object that records a table id and selections.
Use nso_fetch() to execute it, or as_px_query() to inspect the
underlying PXWeb body.
nso_query(tbl_id, selections = list())nso_query(tbl_id, selections = list())
tbl_id |
Table identifier, e.g. "DT_NSO_0300_001V2". |
selections |
Named list mapping dimension labels (e.g., Year, Sex) to desired codes or labels. |
An object of class nso_query.
# Create a query object (does not require network) q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023", Sex = "Total")) print(q)# Create a query object (does not require network) q <- nso_query("DT_NSO_0300_001V2", list(Year = "2023", Sex = "Total")) print(q)
Crawls the PXWeb API to rebuild the table index. If path is provided,
the index is written to that file; otherwise only the in-memory index is
refreshed.
nso_rebuild_px_index( path = NULL, write = !is.null(path), allow_incomplete = FALSE )nso_rebuild_px_index( path = NULL, write = !is.null(path), allow_incomplete = FALSE )
path |
Output path for JSON. If |
write |
Whether to write JSON to |
allow_incomplete |
Allow a partial crawl to replace the current index
and be written to disk. Defaults to |
A tibble containing the rebuilt table index. If some catalogue
requests fail, the index is built from the rest and a warning of class
mongolstats_incomplete_index names the failed paths.
# Crawls the entire PXWeb catalogue; takes several minutes ## Not run: idx <- nso_rebuild_px_index() head(idx) ## End(Not run)# Crawls the entire PXWeb catalogue; takes several minutes ## Not run: idx <- nso_rebuild_px_index() head(idx) ## End(Not run)
Searches table titles in the catalogue (see nso_tables()),
case-insensitively, in English and Mongolian by default. query is a
regular expression unless fixed = TRUE.
nso_search( query, sector = NULL, fields = c("tbl_eng_nm", "tbl_nm"), fixed = FALSE, live = FALSE )nso_search( query, sector = NULL, fields = c("tbl_eng_nm", "tbl_nm"), fixed = FALSE, live = FALSE )
query |
Search string (regex, case-insensitive). |
sector |
Optional sector or sub-sector path (an |
fields |
Character vector of fields to search within. |
fixed |
If |
live |
Use the live PXWeb keyword search instead of the bundled title
index. The source's search semantics apply; regex matching and |
Tibble of matching tables.
nso_search("population") nso_search("infant mortality", sector = "Education, health") nso_search("c++", fixed = TRUE)nso_search("population") nso_search("infant mortality", sector = "Education, health") nso_search("c++", fixed = TRUE)
Queries the PXWeb API root to return the top-level statistical sectors
(e.g., Population, Economy, Environment). Use the returned id column
with nso_subsectors() to drill into sub-categories.
nso_sectors()nso_sectors()
A tibble with columns id, type, and text. In offline mode
(see nso_offline_enable()) an empty tibble is returned; failed
requests raise an error of class mongolstats_http_error.
sectors <- nso_sectors() head(sectors)sectors <- nso_sectors() head(sectors)
Navigates one level deeper in the PXWeb catalogue hierarchy. Pass in a
path id obtained from nso_sectors() or a previous nso_subsectors()
call to list its children (sub-sectors or tables).
nso_subsectors(subid)nso_subsectors(subid)
subid |
Path id from |
A tibble with columns: id, type, text. In offline mode
(see nso_offline_enable()) an empty tibble is returned; failed
requests raise an error of class mongolstats_http_error.
sectors <- nso_sectors() nso_subsectors(sectors$id[1])sectors <- nso_sectors() nso_subsectors(sectors$id[1])
Fetching a table may supply source information unavailable in its dimension codebook. Inspect a fetched result to see this information. Passing a PXWeb table identifier retrieves its title and dimensions; it does not request observations or infer missing source information.
nso_table_info(x)nso_table_info(x)
x |
A fetched result, a provenance manifest, or one PXWeb table ID. |
A tibble with one row per provenance record: service, source ID, title, source statement, update time, unit, URL, retrieval time, and source metadata in a list-column. Fields absent upstream remain missing.
# An unannotated data frame has no source information to report. observations <- data.frame(value = c(12, 15)) nso_table_info(observations) nso_table_info(nso_provenance(observations))# An unannotated data frame has no source information to report. observations <- data.frame(value = c(12, 15)) nso_table_info(observations) nso_table_info(nso_provenance(observations))
Returns a tibble with one row per dimension and a codes list-column,
where each element is a tibble of codes and labels (code, label_en,
label_mn). Useful for manual query assembly and for inspecting available
categories per dimension.
nso_table_meta(tbl_id)nso_table_meta(tbl_id)
tbl_id |
Table identifier (e.g., "DT_NSO_0300_001V2"). |
A tibble with columns: dim (display name), code (dimension code),
is_time (whether it is the table's time dimension), n_values
(integer), and codes (list of tibbles).
In offline mode (see nso_offline_enable()) an empty tibble is
returned; failed requests raise an error of class
mongolstats_http_error.
meta <- nso_table_meta("DT_NSO_0300_001V2") metameta <- nso_table_meta("DT_NSO_0300_001V2") meta
Finds the table's time dimension (years, quarters, months or dates) and lists its periods from oldest to newest.
nso_table_periods(tbl_id)nso_table_periods(tbl_id)
tbl_id |
Table identifier. |
NSO codes periods by position: code "0" is the latest period, so a
period's code changes whenever a new one is published. Use the label
column (or nso_period_seq()) in selections, not code.
A tibble with one row per period, oldest first, and columns
code (the positional PXWeb code), label (as shown by NSO, e.g.
"2024" or "2024-03"), date (first day of the period, see
nso_period_date()) and frequency ("year", "quarter", "month"
or "day"). Periods whose label is not a recognisable date keep their
catalogue order at the end. The tibble has no rows when the table has no
time dimension or in offline mode (see nso_offline_enable()). Unknown
tables and failed requests raise an error.
nso_latest_periods() for the most recent periods.
periods <- nso_table_periods("DT_NSO_0300_001V2") tail(periods)periods <- nso_table_periods("DT_NSO_0300_001V2") tail(periods)
Lists every statistical table in the National Statistics Office PXWeb
catalogue. The list comes from an index bundled with the package, so it
needs no network access; nso_rebuild_px_index() refreshes it from the
API. Tables that NSO publishes or moves after the index was built are
still found by the other functions, which consult the live catalogue.
nso_tables()nso_tables()
A tibble with one row per table and the columns px_path
(catalogue folder), px_file, tbl_id, tbl_eng_nm and tbl_nm
(English and Mongolian titles), strt_prd and end_prd (first and last
period), updated (when NSO last updated the table, as recorded in the
index) and list_id (same as px_path).
nso_search() to find tables by keyword.
tables <- nso_tables() tablestables <- nso_tables() tables
Returns source values separately from numeric observations. Unknown source
symbols are preserved without assigning them an undocumented meaning.
Status is "observed" for finite numbers, "missing" for empty or missing
values, and "symbol" for other source text, including non-finite numbers.
Save this table alongside transformed or exported data because ordinary
transformations may discard attributes.
nso_value_status(x)nso_value_status(x)
x |
A result from |
A tibble containing observation keys, value_raw, and value_status,
or an empty tibble if source status was not retained.
# Constructed records illustrate numeric values and an unresolved symbol. observations <- data.frame( period = c("2023", "2024"), value = c(12, NA_real_), value_raw = c("12", ".."), value_status = c("observed", "symbol") ) nso_value_status(observations) # Ordinary data without retained status have no source-value records. nso_value_status(data.frame(value = 12))# Constructed records illustrate numeric values and an unresolved symbol. observations <- data.frame( period = c("2023", "2024"), value = c(12, NA_real_), value_raw = c("12", ".."), value_status = c("observed", "symbol") ) nso_value_status(observations) # Ordinary data without retained status have no source-value records. nso_value_status(data.frame(value = 12))
Returns every dimension value of a table, with its code and its labels in
English and Mongolian. Use it to find the codes or labels to pass in
selections.
nso_variables(tbl_id)nso_variables(tbl_id)
tbl_id |
Table identifier (e.g., "DT_NSO_0300_001V2"). |
A tibble with one row per dimension value and the columns field
(dimension name), itm_id (value code), scr_eng and scr_mn (English
and Mongolian labels), px_path and px_file. In offline mode (see
nso_offline_enable()) an empty tibble is returned; failed requests
raise an error of class mongolstats_http_error.
nso_dims() for one row per dimension, nso_dim_values() for
the values of one dimension.
vars <- nso_variables("DT_NSO_0300_001V2") varsvars <- nso_variables("DT_NSO_0300_001V2") vars
JSON sidecars preserve source identity and query context separately from
CSV exports or transformed tibbles. Save nso_value_status() separately for
successful results when source symbols matter. Failed fetch manifests retain
status from completed chunks when available. Both reading and writing validate
the manifest schema. Reading accepts local files; replacement writes preserve
the previous file if installing the new file fails.
nso_write_manifest(x, path, overwrite = FALSE) nso_read_manifest(path)nso_write_manifest(x, path, overwrite = FALSE) nso_read_manifest(path)
x |
A fetched result, fetch error condition, or provenance manifest. |
path |
JSON file path. |
overwrite |
Whether to replace an existing file. Defaults to |
nso_write_manifest() returns path invisibly;
nso_read_manifest() returns an nso_manifest.
# An unannotated table produces an empty provenance manifest. observations <- data.frame(value = c(12, 15)) path <- tempfile(fileext = ".json") nso_write_manifest(observations, path) saved <- nso_read_manifest(path) identical(saved, nso_provenance(observations)) unlink(path)# An unannotated table produces an empty provenance manifest. observations <- data.frame(value = c(12, 15)) path <- tempfile(fileext = ".json") nso_write_manifest(observations, path) saved <- nso_read_manifest(path) identical(saved, nso_provenance(observations)) unlink(path)