Package {cnefetools}


Title: Access and Analysis of Brazilian CNEFE Address Data
Version: 0.4.0
Description: Download, cache and read municipality-level address data from the Cadastro Nacional de Enderecos para Fins Estatisticos (CNEFE) of the 2022 Brazilian Census, published by the Instituto Brasileiro de Geografia e Estatistica (IBGE) https://ftp.ibge.gov.br/Cadastro_Nacional_de_Enderecos_para_Fins_Estatisticos/. Beyond data access, provides spatial aggregation of addresses, computation of land-use mix indices, and dasymetric interpolation of census tract variables using CNEFE dwelling points as ancillary data. Results can be produced on 'H3' hexagonal grids or user-supplied polygons, and heavy operations leverage a 'DuckDB' backend with extensions for fast, in-process execution.
License: MIT + file LICENSE
Encoding: UTF-8
URL: https://github.com/pedreirajr/cnefetools, https://pedreirajr.github.io/cnefetools/
BugReports: https://github.com/pedreirajr/cnefetools/issues
Suggests: ggplot2, kableExtra, knitr, leafsync, mapview, odbr, rmarkdown, scales, testthat (≥ 3.0.0), zip
Config/testthat/edition: 3
Depends: R (≥ 4.4.0)
Imports: arrow, dplyr, sf, geobr (≥ 2.0.0), lifecycle, rlang, h3jsr, tidyr, DBI, duckdb, duckspatial (≥ 1.0.0), cli (≥ 3.6.0), checkmate, fs, httr2, piggyback, withr
LazyData: true
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-12-01 02:18:19 UTC; jorge
Author: Jorge Ubirajara Pedreira Junior ORCID iD [aut, cre, cph], Bruno Mioto [aut], Kaio Cunha Pedreira [ctb]
Maintainer: Jorge Ubirajara Pedreira Junior <jorge.ubirajara@ufba.br>
Repository: CRAN
Date/Publication: 2026-12-01 03:50:02 UTC

cnefetools: Access and Analysis of Brazilian CNEFE Address Data

Description

logo

Download, cache and read municipality-level address data from the Cadastro Nacional de Enderecos para Fins Estatisticos (CNEFE) of the 2022 Brazilian Census, published by the Instituto Brasileiro de Geografia e Estatistica (IBGE) https://ftp.ibge.gov.br/Cadastro_Nacional_de_Enderecos_para_Fins_Estatisticos/. Beyond data access, provides spatial aggregation of addresses, computation of land-use mix indices, and dasymetric interpolation of census tract variables using CNEFE dwelling points as ancillary data. Results can be produced on 'H3' hexagonal grids or user-supplied polygons, and heavy operations leverage a 'DuckDB' backend with extensions for fast, in-process execution.

Package options

cnefetools.duckdb_config takes a named list of DuckDB settings, applied to every connection the package opens:

options(cnefetools.duckdb_config = list(threads = 4, memory_limit = "4GB"))

Left unset, DuckDB sizes itself against the whole machine, taking one thread per logical core and a memory_limit of 80% of installed RAM. That is the right default on a dedicated machine and the wrong one on a shared node, a laptop running other work, or a CI runner.

Names are passed to DuckDB's SET verbatim, so any setting DuckDB accepts works, not only these two. An unrecognized name raises an error naming it.

Going over memory_limit makes DuckDB spill to its temporary directory rather than fail, so a low value costs time, not correctness.

The download cache location is set through the CNEFETOOLS_CACHE_DIR environment variable rather than an option. See clear_cache_muni() and clear_cache_tracts().

Author(s)

Maintainer: Jorge Ubirajara Pedreira Junior jorge.ubirajara@ufba.br (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Delete cached municipality boundaries

Description

clear_cache_boundaries() removes the municipality boundaries stored in the user cache directory. The functions that build an H3 grid from code_muni, or that find the municipalities a layer reaches with scope = "geom", read the boundaries at full resolution from a file published with the package and keep each municipality they read in the cache, so later calls work offline. Each file is small (Salvador takes about 0.06 MB, and the 39 municipalities of the São Paulo metropolitan region about 1.6 MB), and the whole country would take about 250 MB.

Usage

clear_cache_boundaries(
  code_muni = "all",
  verbose = TRUE,
  cache_dir = NULL,
  year = NULL
)

Arguments

code_muni

Integer or "all". If "all" (default), every cached boundary is deleted. Otherwise, one or more seven-digit IBGE municipality codes whose boundaries are deleted.

verbose

Logical; if TRUE (default), reports the number of files deleted and the space freed.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

year

Integer. Restrict the deletion to one CNEFE edition. NULL (default) clears every edition, which is the previous behavior.

Value

Invisibly, the character vector of deleted file paths.

Examples


# Delete every cached boundary
clear_cache_boundaries()

# Delete only the boundary of Lauro de Freitas-BA
clear_cache_boundaries(2919207)



Delete cached CNEFE data files

Description

clear_cache_muni() removes CNEFE data files stored in the user cache directory by cnefe_counts(), compute_lumi(), tracts_to_h3(), and related functions.

The cache holds gzipped CSVs (.csv.gz). Archives left by versions before 0.3.0, which cached the ZIP as published by IBGE, are removed as well.

Usage

clear_cache_muni(
  code_muni = "all",
  verbose = TRUE,
  cache_dir = NULL,
  year = NULL
)

Arguments

code_muni

Integer or "all". If "all" (default), every cached CNEFE file is deleted. If a seven-digit IBGE municipality code is provided, only the file for that municipality is deleted.

verbose

Logical; if TRUE (default), reports the number of files deleted and the space freed.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

year

Integer. Restrict the deletion to one CNEFE edition. NULL (default) clears every edition, which is the previous behavior.

Value

Invisibly, the character vector of deleted file paths.

Examples


# Delete every cached CNEFE file
clear_cache_muni()

# Delete only the file for Lauro de Freitas-BA
clear_cache_muni(2919207)



Delete cached census tract Parquet files

Description

clear_cache_tracts() removes census tract Parquet files stored in the user cache directory by tracts_to_h3() and tracts_to_polygon().

Those functions download only the census tracts of the municipalities they read, and keep one file per municipality in the cache. A whole-state file is kept instead when it was downloaded by an earlier version of the package, or when the tracts of a single municipality could not be read from the release. Both kinds of file are removed here.

Usage

clear_cache_tracts(uf = "all", verbose = TRUE, cache_dir = NULL, year = NULL)

Arguments

uf

"all", a two-letter UF abbreviation (e.g. "BA"), a two-digit numeric state code (e.g. 29L), or a seven-digit IBGE municipality code (e.g. 2919207). If "all" (default), all cached Parquet files are deleted. Otherwise, only the files of the resolved state are deleted (the state file and the files of each of its municipalities).

verbose

Logical; if TRUE (default), reports the number of files deleted and the space freed.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

year

Integer. Restrict the deletion to one CNEFE edition. NULL (default) clears every edition, which is the previous behavior.

Value

Invisibly, the character vector of deleted file paths.

Examples


# Delete all cached census tract Parquets
clear_cache_tracts()

# Delete only the Parquet for Bahia (several equivalent calls)
clear_cache_tracts("BA")
clear_cache_tracts(29)
clear_cache_tracts(2919207)  # municipality code → state resolved automatically



Count CNEFE address species on a spatial grid

Description

cnefe_counts() reads CNEFE records for one or more municipalities, assigns each address point to spatial units (either H3 hexagonal cells or user-provided polygons), and returns per-unit counts of COD_ESPECIE as addr_type1 to addr_type8.

Usage

cnefe_counts(
  code_muni = NULL,
  year = 2022,
  polygon_type = lifecycle::deprecated(),
  polygon = NULL,
  crs_output = NULL,
  h3_resolution = 9,
  scope = c("muni", "geom"),
  verbose = TRUE,
  cache = TRUE,
  cache_dir = NULL,
  backend = c("duckdb", "r")
)

Arguments

code_muni

Numeric or character. One or more seven-digit IBGE municipality codes, for example 2927408 or c(2927408, 2919207). Repeated codes are dropped. With several codes, their addresses are counted together (see "Several municipalities").

Required for the H3 grid, which is built from the boundaries of these municipalities. With polygon, it's required under scope = "muni" and ignored under scope = "geom", which finds the municipalities that the polygons intersect (see "Municipalities detected from the polygons").

year

Integer. The CNEFE data year. Currently only 2022 is supported. Defaults to 2022.

polygon_type

[Deprecated] The aggregation mode is now inferred from polygon: leave it NULL for an H3 grid, or pass an sf::sf object for user polygons. Passing polygon_type still works and warns.

polygon

An sf::sf object with polygon geometries. When it's supplied, the counts are returned for these polygons instead of an H3 grid. Features with the same geometry as an earlier feature are dropped, with a message, and the first one is kept. Under scope = "muni", a warning reports how many addresses of the municipalities in code_muni fall outside the polygons. When polygons overlap, a warning also reports how many addresses fall in more than one of them, since those are counted in each. If no address falls inside the polygons, the function stops with an error.

crs_output

The CRS for the output object. Only used when polygon is supplied. Default is NULL, which uses the original CRS of the polygon argument. Can be an EPSG code (e.g., 4326, 31983) or any CRS object accepted by sf::st_transform().

h3_resolution

Integer. H3 grid resolution (default: 9). Only used for the H3 grid, so it is ignored when polygon is supplied.

scope

Character. Which CNEFE addresses the function works with. "muni" (the default, and the faster option) uses every address of the municipalities in code_muni. "geom" uses the addresses that fall inside the output geometries (the H3 cells, or the polygons in polygon), whichever municipality they belong to, so the municipalities those geometries reach are read as well. The H3 grid holds the cells whose center falls inside the boundaries of code_muni, plus the neighboring cells that intersect those boundaries. See the section "Border cells at the edge of the region".

verbose

Logical; if TRUE, prints messages and timing information.

cache

Logical. If TRUE (default), the downloaded files are kept in the user cache directory and reused in later calls. These are the CNEFE file of each municipality, stored as a gzipped CSV, and the municipal boundaries used to build the H3 grid or to find the municipalities that the polygons reach, one small file per municipality. If FALSE, temporary files are used and deleted after the call. See clear_cache_muni() and clear_cache_boundaries() to delete the cached files.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

backend

Character. "duckdb" (default) uses DuckDB with the H3 extension, and the spatial extension as well when polygon is supplied. "r" uses h3jsr and sf in R instead, and needs no DuckDB extension for the counts. The municipal boundaries of the H3 grid are still downloaded through DuckDB's httpfs extension the first time, on either backend, and if that fails the simplified geobr boundaries are used instead.

"r" exists for environments where DuckDB extensions cannot be installed, such as some restricted computing clusters. It is not the lighter option: it materializes the filtered address table in R memory, so its footprint grows with the municipality, while DuckDB aggregates in a streaming fashion and stays nearly flat. On São Paulo (5.7 million addresses) the measured peak is about 8.8 GB under "r" against 0.7 GB under "duckdb", alongside being roughly 22 times slower.

If the constraint is memory rather than installability, keep the DuckDB backend and cap it with the cnefetools.duckdb_config option instead. See ?cnefetools for that option, and the benchmark article at https://pedreirajr.github.io/cnefetools/articles/bench_duckdb.html for the measurements.

Details

The counts in the columns addr_type1 to addr_type8 correspond to:

All eight types are reported. In particular, addr_type7 is retained here, whereas compute_lumi() excludes it when computing land-use mix indices.

Several municipalities

Pass a vector of codes to cover a region that spans more than one municipality. The records of all of them are counted together on one grid built over the union of the boundaries, so every cell appears once.

Calling the function once per municipality and binding the results isn't the same. A cell on a shared border belongs to the grid of both municipalities, so it comes back from both calls, each with only the addresses of its own municipality (under the default scope = "muni"). Counts add up, so those outputs can be combined by summing addr_type1 to addr_type8 by id_hex, but dropping the repeated rows (for example with dplyr::distinct()) loses one side of the border. Shares and indices shouldn't be averaged across municipalities. Compute them from the summed counts, or use compute_lumi() with a vector of codes.

Large requests

Before downloading anything, the function looks up the size of each municipality's file and its number of addresses in an internal table. With verbose = TRUE, it reports how much will be downloaded and how many addresses will be processed. A warning of class cnefetools_large_request, shown even with verbose = FALSE, flags a call that processes more than 20 million addresses (3 million under backend = "r", which holds them in memory), or that downloads more than 1 GB. The call still runs. To silence the warning, wrap the call in suppressWarnings(classes = "cnefetools_large_request").

Border cells at the edge of the region

Under the default scope = "muni", only the addresses of the municipalities in code_muni are read. A cell or polygon on the outer edge of the requested area, one that also overlaps a municipality you did not request, therefore describes only the part of it that lies inside the area: its counts leave out the addresses of the neighbor. Adding municipalities moves the edge outward but does not remove it.

Under scope = "geom", the municipalities that the output geometries reach are read too, and every cell or polygon receives all the addresses inside it, so the edge is complete. On the H3 grid, code_muni still defines the grid, and a message lists the neighboring municipalities read to complete it. This costs a download and a read of each of them in full, which is why it is not the default.

Addresses outside the H3 grid

The grid is built from the 2022 IBGE municipal boundaries, at full resolution, plus the ring of cells along them, but each address goes to the cell of its own coordinates. An address geocoded beyond that ring, for example on the coast or on a small island the boundary doesn't follow, lands in a cell outside the grid and isn't counted. A warning reports how many addresses of the municipalities in code_muni this affects, so the counts can be reconciled with their CNEFE totals. Under scope = "geom", the addresses of the neighboring municipalities that fall beyond the grid are expected and not reported.

Municipalities detected from the polygons

When polygon is supplied with scope = "geom", the function finds the municipalities that the polygons intersect, using the 2022 IBGE municipal boundaries, and reads all of their addresses. A message lists them, and a code_muni passed in this case is ignored.

Polygons from another source rarely follow the IBGE boundaries exactly, so a polygon along a municipal border can touch a neighboring municipality by a few meters. That neighbor is then downloaded and read too. The counts are not affected, since only the points inside the polygons are counted, but use scope = "muni" with code_muni whenever you know which municipalities the polygons belong to, which is faster.

Value

An sf::sf object containing:

When polygon is supplied, the output CRS matches the original polygon CRS (or crs_output if specified).

See Also

compute_lumi() for land-use mix indices on the same spatial units.

Examples


# Count addresses per H3 hexagon (resolution 9)
hex_counts <- cnefe_counts(code_muni = 2929057, cache = FALSE)

# Several municipalities in one call: one grid over their union, with no cell
# repeated along the shared border (Salvador and its neighbor Lauro de Freitas)
region_counts <- cnefe_counts(code_muni = c(2927408, 2919207), cache = FALSE)

# The grid of Lauro de Freitas, with the cells along its border completed by
# the addresses of the neighboring municipalities
ldf_full <- cnefe_counts(code_muni = 2919207, scope = "geom", cache = FALSE)

# Count addresses per user-provided polygon (neighborhoods of Lauro de Freitas-BA)
# Using geobr to download neighborhood boundaries
library(geobr)
nei_ldf <- subset(
  read_neighborhood(year = 2022),
  code_muni == 2919207
)
nei_counts <- cnefe_counts(
  code_muni = 2919207,
  polygon = nei_ldf,
  cache = FALSE
)

# With scope = "geom", the municipalities the polygons intersect are read
nei_counts_auto <- cnefe_counts(polygon = nei_ldf, scope = "geom", cache = FALSE)



Open the official CNEFE data dictionary

Description

Opens the bundled Excel data dictionary in the system's default spreadsheet viewer (e.g., Excel, LibreOffice).

Usage

cnefe_dictionary(year = 2022)

Arguments

year

Integer. The CNEFE data year. Currently only 2022 is supported.

Value

Invisibly, the path to the Excel file inside the installed package.

Examples


cnefe_dictionary()


Open the official CNEFE methodological note

Description

Opens the bundled PDF methodological document in the system's default PDF viewer.

Usage

cnefe_doc(year = 2022)

Arguments

year

Integer. The CNEFE data year. Currently only 2022 is supported.

Value

Invisibly, the path to the PDF file inside the installed package.

Examples


cnefe_doc()


Export CNEFE data to a persistent, optimized file

Description

cnefe_export() downloads a municipality (or reuses the cache) and writes it to a location and format of your choosing, so the data no longer depends on the package cache being present or on the IBGE server being reachable.

Usage

cnefe_export(
  code_muni,
  path,
  format = c("parquet", "csv", "csv.gz"),
  year = 2022,
  overwrite = FALSE,
  cache = TRUE,
  cache_dir = NULL,
  verbose = TRUE
)

Arguments

code_muni

Integer. Seven-digit IBGE municipality code.

path

Character. Directory to write into. Created if missing.

format

Character. "parquet" (default), "csv" or "csv.gz".

year

Integer. The CNEFE data year. Currently only 2022 is supported.

overwrite

Logical. Whether to replace an existing file. Defaults to FALSE, which errors instead, since these files are expensive to produce.

cache

Logical. Whether to use the package cache for the download.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache".

verbose

Logical. Whether to print progress.

Details

The package cache is designed to be transient: it lives in a directory the package manages, it holds the ZIP exactly as IBGE published it, and clear_cache_muni() is expected to empty it. That is the wrong shape for a reproducible analysis that must still run in a year.

This function fills that gap. Point it at a project directory, a shared volume or an external drive, choose a format, and use the resulting file directly:

path <- cnefe_export(2919207, "data/cnefe")
cnefe <- read_cnefe(file = path)

read_cnefe() accepts any file this function writes, and also the raw ZIP as distributed by IBGE, so a file obtained by other means can be read without the download step at all.

Parquet is the default because it is columnar, typed and compressed, which makes it markedly smaller and faster to read than the published CSV, and because it is the format Arrow and DuckDB both read natively.

Value

The path to the written file, invisibly.

See Also

read_cnefe(), which reads the result back through its file argument, and clear_cache_muni() for the transient cache.

Examples


# Write a municipality to a project directory as Parquet
path <- cnefe_export(2929057, path = tempdir(), cache = FALSE, overwrite = TRUE)

# Read it back without touching the network
cnefe <- read_cnefe(file = path)



Compute land-use mix indicators on a spatial grid

Description

compute_lumi() reads CNEFE records for one or more municipalities, assigns each address point to spatial units (either H3 hexagonal cells or user-provided polygons), and computes the residential proportion (p_res) and land-use mix indices, such as the Entropy Index (ei), the Herfindahl-Hirschman Index (hhi), the Balance Index (bal), the Index of Concentration at Extremes (ice), the adapted HHI (hhi_adp), and the Bidirectional Global-centered Balance Index (bgbi), following the methodology proposed in Pedreira Junior et al. (2025, 2026). The 2026 article introduces the BGBI, and the adapted HHI is documented in the 2025 preprint.

Usage

compute_lumi(
  code_muni = NULL,
  year = 2022,
  polygon_type = lifecycle::deprecated(),
  polygon = NULL,
  crs_output = NULL,
  h3_resolution = 9,
  scope = c("muni", "geom"),
  p_target = NULL,
  verbose = TRUE,
  cache = TRUE,
  cache_dir = NULL,
  backend = c("duckdb", "r")
)

Arguments

code_muni

Numeric or character. One or more seven-digit IBGE municipality codes, for example 2927408 or c(2927408, 2919207). Repeated codes are dropped. With several codes, their addresses are pooled into one analysis (see "Several municipalities").

Required for the H3 grid, which is built from the boundaries of these municipalities. With polygon, it's required under scope = "muni" and ignored under scope = "geom", which finds the municipalities that the polygons intersect (see "Municipalities detected from the polygons").

year

Integer. The CNEFE data year. Currently only 2022 is supported. Defaults to 2022.

polygon_type

[Deprecated] The aggregation mode is now inferred from polygon: leave it NULL for an H3 grid, or pass an sf::sf object for user polygons. Passing polygon_type still works and warns.

polygon

An sf::sf object with polygon geometries. When it's supplied, the indices are computed for these polygons instead of an H3 grid. Features with the same geometry as an earlier feature are dropped, with a message, and the first one is kept. Under scope = "muni", a warning reports how many addresses of the municipalities in code_muni fall outside the polygons. When polygons overlap, a warning also reports how many addresses fall in more than one of them, since those enter the indices of each. If no address falls inside the polygons, the function stops with an error.

crs_output

The CRS for the output object. Only used when polygon is supplied. Default is NULL, which uses the original CRS of the polygon argument. Can be an EPSG code (e.g., 4326, 31983) or any CRS object accepted by sf::st_transform().

h3_resolution

Integer. H3 grid resolution (default: 9). Only used for the H3 grid, so it is ignored when polygon is supplied.

scope

Character. Which CNEFE addresses the function works with. "muni" (the default, and the faster option) uses every address of the municipalities in code_muni. "geom" uses the addresses that fall inside the output geometries (the H3 cells, or the polygons in polygon), whichever municipality they belong to, so the municipalities those geometries reach are read as well. The H3 grid holds the cells whose center falls inside the boundaries of code_muni, plus the neighboring cells that intersect those boundaries. The scope also decides which addresses P comes from (see "The citywide baseline P").

p_target

Numeric or NULL. A single number strictly between 0 and 1 that replaces the observed P, for example a residential share set by a land-use plan (⁠P*⁠ in Pedreira Junior et al., 2026). NULL (the default) computes P from the data (see "The citywide baseline P").

verbose

Logical; if TRUE, prints messages and timing information.

cache

Logical. If TRUE (default), the downloaded files are kept in the user cache directory and reused in later calls. These are the CNEFE file of each municipality, stored as a gzipped CSV, and the municipal boundaries used to build the H3 grid or to find the municipalities that the polygons reach, one small file per municipality. If FALSE, temporary files are used and deleted after the call. See clear_cache_muni() and clear_cache_boundaries() to delete the cached files.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

backend

Character. "duckdb" (default) uses DuckDB with the H3 extension, reading the cached gzipped CSV directly. "r" computes H3 in R using h3jsr instead, and needs no DuckDB extension for the indices. The municipal boundaries of the H3 grid are still downloaded through DuckDB's httpfs extension the first time, on either backend, and if that fails the simplified geobr boundaries are used instead.

"r" exists for environments where DuckDB extensions cannot be installed, such as some restricted computing clusters. It is not the lighter option: it materializes the filtered address table in R memory, so its footprint grows with the municipality, while DuckDB aggregates in a streaming fashion and stays nearly flat. On São Paulo (5.7 million addresses) the measured peak is about 8.7 GB under "r" against 0.7 GB under "duckdb", alongside being roughly 22 times slower.

If the constraint is memory rather than installability, keep the DuckDB backend and cap it with the cnefetools.duckdb_config option instead. See ?cnefetools for that option, and the benchmark article at https://pedreirajr.github.io/cnefetools/articles/bench_duckdb.html for the measurements.

Details

Binary land-use classification

The indices computed here rest on a binary split. An address is counted as residential when COD_ESPECIE == 1 (private household), and as non-residential otherwise. This follows the formulation of the indices as published in Pedreira Junior et al. (2026), where the measures are defined and empirically validated on that two-category basis.

Exclusion of buildings under construction

compute_lumi() drops records with COD_ESPECIE == 7 (building under construction or renovation), because such records describe a transitional state rather than a realized land use. Note that cnefe_counts() does not apply this exclusion and reports these records as addr_type7.

The citywide baseline P

Two indices use a citywide residential share P: the bgbi index, which is referenced against it, and the Balance Index (bal), which uses it through r = P / (1 - P). The other indices are computed entirely within each spatial unit. Two properties of P are worth stating.

First, P is computed from CNEFE address-type counts rather than from census population, so it describes the distribution of address types and not the distribution of residents.

Second, by default (scope = "muni") P is computed from every CNEFE address of the municipalities in code_muni, including when polygon is supplied, so it does not adapt to the area the supplied polygons happen to cover. This is intended, as P describes the context the addresses sit in, which is the municipality (or the region, when several are read), and a sub-area of a city is still part of that wider context.

scope = "geom" computes P from the addresses inside the output geometries instead, each counted once where polygons overlap, which measures mix relative to the area covered rather than relative to the city. For polygons that cover only part of a municipality, such as a set of central neighborhoods, P is then the residential share of those polygons alone. On an H3 grid, P becomes the share of the cells of the grid, including the addresses of the neighboring municipalities that fall in the cells along the border.

p_target replaces P with a composition chosen by the analyst, such as a goal set by a land-use plan, a zoning reform or a transit-oriented development strategy. This is the extension proposed in the conclusions of Pedreira Junior et al. (2026). With it, bgbi measures the distance to that goal rather than to the observed city, and the same target can be used across municipalities so that their values become comparable. bal with a target is no longer the original Balance Index of Song et al. (2013), which is defined against the observed citywide ratio.

Several municipalities

Pass a vector of codes to cover a region that spans more than one municipality. The records of all of them are pooled before anything is computed, the H3 grid is built over the union of their boundaries, and P is the residential share of the whole region. Each cell appears once, and a cell on a shared border holds the addresses of both sides.

Because P belongs to the region, bal and bgbi are measured against the regional share, not against each municipality's own, and adding a municipality to code_muni changes them in every unit, not only near it. A call per municipality gives each of them a different P, so indices from such calls aren't comparable with one another, nor with a regional call.

Large requests

Before downloading anything, the function looks up the size of each municipality's file and its number of addresses in an internal table. With verbose = TRUE, it reports how much will be downloaded and how many addresses will be processed. A warning of class cnefetools_large_request, shown even with verbose = FALSE, flags a call that processes more than 20 million addresses (3 million under backend = "r", which holds them in memory), or that downloads more than 1 GB. The call still runs. To silence the warning, wrap the call in suppressWarnings(classes = "cnefetools_large_request").

Border cells at the edge of the region

Under the default scope = "muni", only the addresses of the municipalities in code_muni are read. A cell or polygon on the outer edge of the requested area, one that also overlaps a municipality you did not request, therefore describes only the part of it that lies inside the area: its values (counts, p_res and indices) leave out the addresses of the neighbor. Adding municipalities moves the edge outward but does not remove it, and changes P.

Under scope = "geom", the municipalities that the output geometries reach are read too, and every cell or polygon receives all the addresses inside it, so the edge is complete. On the H3 grid, code_muni still defines the grid, and a message lists the neighboring municipalities read to complete it. This costs a download and a read of each of them in full, which is why it is not the default.

Addresses outside the H3 grid

The grid is built from the 2022 IBGE municipal boundaries, at full resolution, plus the ring of cells along them, but each address goes to the cell of its own coordinates. An address geocoded beyond that ring, for example on the coast or on a small island the boundary doesn't follow, lands in a cell outside the grid and isn't counted. A warning reports how many addresses of the municipalities in code_muni this affects. With scope = "muni" they are still part of P, and with scope = "geom" they are not.

Municipalities detected from the polygons

When polygon is supplied with scope = "geom", the function finds the municipalities that the polygons intersect, using the 2022 IBGE municipal boundaries, and reads all of their addresses. A message lists them, and a code_muni passed in this case is ignored.

Polygons from another source rarely follow the IBGE boundaries exactly, so a polygon along a municipal border can touch a neighboring municipality by a few meters. That neighbor is then downloaded and read too. Neither P nor the indices change, since only the addresses inside the polygons are used. If you know which municipalities the polygons belong to and want P to describe them, use scope = "muni" with code_muni, which is also faster.

Value

An sf::sf object containing:

When polygon is NULL (H3 grid):
  • id_hex: H3 cell identifier

  • p_res, ei, hhi, bal, ice, hhi_adp, bgbi: land-use mix indicators

  • geometry: hexagon geometry (CRS 4326)

When polygon is supplied:
  • Original columns from polygon

  • p_res, ei, hhi, bal, ice, hhi_adp, bgbi: land-use mix indicators

  • geometry: polygon geometry (in the original or crs_output CRS)

References

Pedreira Junior, J. U.; Louro, T. V.; Assis, L. B. M.; Brito, P. L.; Bomfim, F. G. (2026). BGBI: A citywide-referenced and bidirectional land use mix index for planning and policy evaluation. Land Use Policy, 169, 108135. https://doi.org/10.1016/j.landusepol.2026.108135

Pedreira Junior, J. U.; Louro, T. V.; Assis, L. B. M.; Brito, P. L. (2025). Measuring land use mix with address-level census data. engrXiv preprint. https://engrxiv.org/preprint/view/5975 (where the adapted HHI (hhi_adp) is documented)

Massey, D. S. (2001). The prodigal paradigm returns: ecology comes back to sociology. In A. Booth & A. C. Crouter (Eds.), Does It Take a Village? Community Effects on Children, Adolescents, and Families. Lawrence Erlbaum.

Song, Y.; Merlin, L.; Rodriguez, D. (2013). Comparing measures of urban land use mix. Computers, Environment and Urban Systems, 42, 1–13. https://doi.org/10.1016/j.compenvurbsys.2013.08.001

Examples


# Compute land-use mix indices on H3 hexagons
lumi <- compute_lumi(code_muni = 2929057, cache = FALSE)

# Several municipalities in one call: one grid over their union and one P for
# the whole region (Salvador and its neighbor Lauro de Freitas)
lumi_region <- compute_lumi(code_muni = c(2927408, 2919207), cache = FALSE)

# Compute land-use mix indices on user-provided polygons (neighborhoods of Lauro de Freitas-BA)
# Using geobr to download neighborhood boundaries
library(geobr)
nei_ldf <- subset(
  read_neighborhood(year = 2022),
  code_muni == 2919207
)
lumi_poly <- compute_lumi(
  code_muni = 2919207,
  polygon = nei_ldf,
  cache = FALSE
)

# With scope = "geom", the municipalities the polygons intersect are read, and
# P comes from the addresses inside the neighborhoods
lumi_poly_geom <- compute_lumi(polygon = nei_ldf, scope = "geom", cache = FALSE)

# BGBI against a target residential share of 70% instead of the observed one
lumi_target <- compute_lumi(code_muni = 2919207, p_target = 0.7, cache = FALSE)



Read CNEFE data for one or more municipalities

Description

Downloads and reads the CNEFE CSV file for one or more IBGE municipality codes, using the official IBGE FTP structure. The function relies on an internal index linking municipality codes to the corresponding ZIP URLs. Data are returned either as an Arrow Table (default) or as an sf object with SIRGAS 2000 coordinates.

Usage

read_cnefe(
  code_muni = NULL,
  year = 2022,
  verbose = TRUE,
  cache = TRUE,
  cache_dir = NULL,
  output = c("arrow", "sf"),
  file = NULL
)

Arguments

code_muni

Integer. One or more seven-digit IBGE municipality codes. Repeated codes are read only once. Omit it when reading a local file through file.

year

Integer. The CNEFE data year. Currently only 2022 is supported. Defaults to 2022.

verbose

Logical; if TRUE, print informative messages about download, extraction, and reading steps.

cache

Logical; if TRUE, keep the downloaded data as a gzipped CSV in the cache folder (see cache_dir). If FALSE, a temporary file is used and removed after reading.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

output

Character. Output format. "arrow" (default) returns an arrow::Table, whereas "sf" returns an sf point object with coordinates built from LONGITUDE / LATITUDE in CRS 4674.

file

Character. Path to a CNEFE file already on disk, read instead of downloading. Accepts .zip as published by IBGE, .csv, .csv.gz and .parquet, which is what cnefe_export() writes. Mutually exclusive with code_muni, and it makes the function independent of the IBGE server.

Details

When output = "arrow" (default), the function does not perform any spatial conversion and simply returns the Arrow table. When output = "sf", the function converts the result to an sf point object using the LONGITUDE and LATITUDE columns, with CRS EPSG:4674 (SIRGAS 2000), keeping these columns in the final object (remove = FALSE).

When code_muni has several codes, each municipality is read on its own and the results are stacked into one table, in the order the codes were given. The COD_MUNICIPIO column tells the municipalities apart. A column that comes out with different types in different municipalities (for example, one left empty in a small municipality) is converted to a type that fits all of them before stacking.

Value

If output = "arrow", an arrow::Table containing all CNEFE records for the given municipalities.

If output = "sf", an sf object with point geometry in EPSG:4674 (SIRGAS 2000), using the LONGITUDE and LATITUDE columns.

Caching

When cache = TRUE (the default), each municipality is downloaded once and kept as a gzipped CSV, so later calls, in this session or any other, reuse it instead of downloading again. The cache folder is cache_dir when given, otherwise the CNEFETOOLS_CACHE_DIR environment variable when set, otherwise tools::R_user_dir() with which = "cache".

When cache = FALSE, the files are stored in a temporary location and removed when the function exits.

The cache is meant to be cleared (see clear_cache_muni()). For a copy that stays put, use cnefe_export(). The "Cache and exported copies" article on the package website covers both.

Large requests

Before downloading anything, the function looks up the size of each municipality's file and its number of addresses in an internal table. With verbose = TRUE, it reports how much will be downloaded and how many addresses will be read. The whole table is held in memory, so a warning of class cnefetools_large_request, shown even with verbose = FALSE, flags a call that reads more than 10 million addresses with output = "arrow" (about 2.6 GB of RAM), more than 3 million with output = "sf" (about 2 GB), or that downloads more than 1 GB. The call still runs. To silence the warning, wrap the call in suppressWarnings(classes = "cnefetools_large_request").

See Also

cnefe_export() to write a municipality to a persistent, optimized file that this function can read back through file.

Examples


# Read CNEFE data as an Arrow table
cnefe <- read_cnefe(code_muni = 2929057, cache = FALSE)

# Read a local file instead, with no network access. overwrite = TRUE because
# cnefe_export() refuses to clobber an existing export by default.
path <- cnefe_export(2929057, path = tempdir(), cache = FALSE, overwrite = TRUE)
cnefe_local <- read_cnefe(file = path)

# Read as an sf spatial object
cnefe_sf <- read_cnefe(code_muni = 2929057, output = "sf", cache = FALSE)

# Read two municipalities into one table
cnefe_two <- read_cnefe(code_muni = c(2929057, 2919207), cache = FALSE)



Convert census tract aggregates to an H3 grid using CNEFE points

Description

tracts_to_h3() performs a dasymetric interpolation with the following steps:

  1. census tract totals are allocated to CNEFE dwelling points inside each tract;

  2. allocated values are aggregated to an H3 grid at a user-defined resolution.

The function uses DuckDB with the spatial and H3 extensions for the heavy work.

Unlike cnefe_counts() and compute_lumi(), this function does not expose a backend argument and relies on DuckDB exclusively. The dominant cost here is a spatial overlay between the full CNEFE point set of the municipality and the census tract polygons, which is a different workload from the tabular aggregation those other functions perform. Running that overlay in R would take prohibitively long in medium and large municipalities, so a pure-R fallback would offer users a path that does not finish rather than a slower one.

Usage

tracts_to_h3(
  code_muni,
  year = 2022,
  h3_resolution = 9,
  vars = c("pop_ph", "pop_ch"),
  scope = c("muni", "geom"),
  cache = TRUE,
  cache_dir = NULL,
  verbose = TRUE
)

Arguments

code_muni

Numeric or character. One or more seven-digit IBGE municipality codes, for example 2927408 or c(2927408, 2919207). Repeated codes are dropped. With several codes, they're interpolated together (see "Several municipalities"). Always required, since the grid is built from the boundaries of these municipalities.

year

Integer. The CNEFE data year. Currently only 2022 is supported. Defaults to 2022.

h3_resolution

Integer. H3 resolution (0 to 15). Defaults to 9.

vars

Character vector. Names of tract-level variables to interpolate. Supported variables:

  • pop_ph: population in private households (Domicílios particulares).

  • pop_ch: population in collective households (Domicílios coletivos).

  • male: total male population.

  • female: total female population.

  • age_0_4, age_5_9, age_10_14, age_15_19, age_20_24, age_25_29, age_30_39, age_40_49, age_50_59, age_60_69, age_70m: population by age group.

  • race_branca, race_preta, race_amarela, race_parda, race_indigena: population by race/color (cor ou raça).

  • n_resp: number of household heads (Pessoas responsáveis por domicílios).

  • avg_inc_resp: average income of the household heads.

For a reference table mapping these variable names to the official IBGE census tract codes and descriptions, see tracts_variables_ref.

Allocation rules:

  • pop_ph is allocated only to private dwellings.

  • pop_ch is allocated only to collective dwellings.

  • n_resp is allocated only to private dwellings (same rule as pop_ph).

  • Demographic variables (male, female, ⁠age_*⁠, ⁠race_*⁠) are allocated to private dwellings when the tract has any; if the tract has zero private dwellings but has collective dwellings, they are allocated to collective.

  • avg_inc_resp is assigned (not split) to each private dwelling point; tracts with no private dwellings receive no allocation.

scope

Character. Which CNEFE addresses (and census tracts) the function works with. "muni" (the default, and the faster option) uses every address and tract of the municipalities in code_muni. "geom" uses the addresses that fall inside the H3 cells, whichever municipality they belong to, so the municipalities the grid reaches are read as well. The H3 grid holds the cells whose center falls inside the boundaries of code_muni, plus the neighboring cells that intersect those boundaries. See the section "Border cells at the edge of the region".

cache

Logical. If TRUE (default), the downloaded files are kept in the user cache directory and reused in later calls. These are the CNEFE file, the census tracts and the boundary of each municipality read. Only the tracts of those municipalities are downloaded, not the whole state. If FALSE, temporary files are used and deleted after the call. See clear_cache_muni(), clear_cache_tracts() and clear_cache_boundaries() to delete the cached files.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

verbose

Logical. Whether to print step messages and timing.

Details

Several municipalities

Pass a vector of codes to interpolate a region that spans more than one municipality in a single call. The tracts and the CNEFE points of all of them go through one allocation, each point is matched only to the tracts of its own municipality, and the grid is built over the union of the boundaries, so every cell appears once.

Calling the function once per municipality and binding the results isn't the same. A cell on a shared border belongs to the grid of both municipalities, so it comes back from both calls, each with only its own side (under the default scope = "muni"), and dropping the repeated rows loses one side. Totals (every variable except avg_inc_resp) add up, so separate outputs can be combined by summing them by id_hex. avg_inc_resp can't, because it's an average over the allocated points, and two averages don't give the average of the pooled points. Use a vector of codes instead.

Large requests

Before downloading anything, the function looks up the size of each municipality's file and its number of addresses in an internal table. With verbose = TRUE, it reports how much will be downloaded and how many addresses will be processed. A warning of class cnefetools_large_request, shown even with verbose = FALSE, flags a call that processes more than 20 million addresses, or that downloads more than 1 GB. The census tract files are not counted in the download. The call still runs. To silence the warning, wrap the call in suppressWarnings(classes = "cnefetools_large_request").

Border cells at the edge of the region

Under the default scope = "muni", only the addresses and tracts of the municipalities in code_muni are read. A cell on the outer edge of the requested area, one that also overlaps a municipality you did not request, therefore describes only the part of it that lies inside the area: its values (totals and avg_inc_resp) leave out the addresses of the neighbor. Adding municipalities moves the edge outward but does not remove it.

Under scope = "geom", the municipalities that the grid reaches are read too, and every cell receives the allocation of all the dwellings inside it, so the edge is complete. A message lists the neighboring municipalities read. The CNEFE file of each neighbor is read whole, since the files come one per municipality, but only the neighbor's tracts with at least one dwelling inside the grid enter the allocation. Those tracts enter with all their dwellings, so the result matches a call that lists the neighbors in code_muni, restricted to the cells of this grid. It's still slower than "muni", which is why it isn't the default.

Addresses outside the H3 grid

The grid is built from the 2022 IBGE municipal boundaries, at full resolution, plus the ring of cells along them, but each dwelling point goes to the cell of its own coordinates. A point geocoded beyond that ring, for example on the coast or on a small island the boundary doesn't follow, lands in a cell outside the grid, and what was allocated to it isn't in the output. The diagnostics report how many allocated points of the municipalities in code_muni this affects and how much of each total they carried, so the output can be reconciled with the tract totals. Under scope = "geom", the points of the neighboring municipalities that fall beyond the grid are expected and not reported.

Value

An sf object (CRS 4326) with an H3 grid and the requested interpolated variables.

Examples


# Interpolate population to H3 hexagons
hex_pop <- tracts_to_h3(
  code_muni = 2929057,
  vars = c("pop_ph", "pop_ch"),
  cache = FALSE
)



Convert census tract aggregates to user-provided polygons using CNEFE points

Description

tracts_to_polygon() performs a dasymetric interpolation with the following steps:

  1. census tract totals are allocated to CNEFE dwelling points inside each tract;

  2. allocated values are aggregated to user-provided polygons (neighborhoods, administrative divisions, custom areas, etc.).

The function uses DuckDB with spatial extensions for the heavy work.

Unlike cnefe_counts() and compute_lumi(), this function does not expose a backend argument and relies on DuckDB exclusively. The dominant cost here is a spatial overlay between the full CNEFE point set of the municipality and the census tract polygons, which is a different workload from the tabular aggregation those other functions perform. Running that overlay in R would take prohibitively long in medium and large municipalities, so a pure-R fallback would offer users a path that does not finish rather than a slower one.

Usage

tracts_to_polygon(
  code_muni = NULL,
  polygon,
  year = 2022,
  vars = c("pop_ph", "pop_ch"),
  crs_output = NULL,
  scope = c("muni", "geom"),
  cache = TRUE,
  cache_dir = NULL,
  verbose = TRUE
)

Arguments

code_muni

Numeric or character. One or more seven-digit IBGE municipality codes, for example 2927408 or c(2927408, 2919207). Repeated codes are dropped. With several codes, they're interpolated together, in a single allocation (see "Several municipalities").

Required under scope = "muni" (the default) and ignored under scope = "geom", which finds the municipalities that the polygons intersect (see "Municipalities detected from the polygons").

polygon

An sf::sf object with polygon geometries (POLYGON or MULTIPOLYGON), in any CRS. Features with the same geometry as an earlier feature are dropped, with a message, and the first one is kept. Under scope = "muni", the diagnostics report the share of the allocated points of the municipalities in code_muni that falls inside the polygons. When polygons overlap, the diagnostics open with how many dwellings fall in more than one of them, since their allocated values are added to each.

year

Integer. The CNEFE data year. Currently only 2022 is supported. Defaults to 2022.

vars

Character vector. Names of tract-level variables to interpolate. Supported variables:

  • pop_ph: population in private households (Domicílios particulares).

  • pop_ch: population in collective households (Domicílios coletivos).

  • male: total male population.

  • female: total female population.

  • age_0_4, age_5_9, age_10_14, age_15_19, age_20_24, age_25_29, age_30_39, age_40_49, age_50_59, age_60_69, age_70m: population by age group.

  • race_branca, race_preta, race_amarela, race_parda, race_indigena: population by race/color (cor ou raça).

  • n_resp: number of household heads (Pessoas responsáveis por domicílios).

  • avg_inc_resp: average income of the household heads.

For a reference table mapping these variable names to the official IBGE census tract codes and descriptions, see tracts_variables_ref.

Allocation rules:

  • pop_ph is allocated only to private dwellings.

  • pop_ch is allocated only to collective dwellings.

  • n_resp is allocated only to private dwellings (same rule as pop_ph).

  • Demographic variables (male, female, ⁠age_*⁠, ⁠race_*⁠) are allocated to private dwellings when the tract has any; if the tract has zero private dwellings but has collective dwellings, they are allocated to collective.

  • avg_inc_resp is assigned (not split) to each private dwelling point; tracts with no private dwellings receive no allocation.

crs_output

The CRS for the output object. Default is NULL, which uses the original CRS of the polygon argument. Can be an EPSG code (e.g., 4326, 31983) or any CRS object accepted by sf::st_transform().

scope

Character. Which CNEFE addresses (and census tracts) the function works with. "muni" (the default, and the faster option) uses every address and tract of the municipalities in code_muni. "geom" uses the addresses that fall inside the polygons in polygon, whichever municipality they belong to, so the municipalities those polygons reach are read as well. See the section "Polygons at the edge of the region".

cache

Logical. If TRUE (default), the downloaded files are kept in the user cache directory and reused in later calls. These are the CNEFE file, the census tracts and the boundary of each municipality read. Only the tracts of those municipalities are downloaded, not the whole state. If FALSE, temporary files are used and deleted after the call. See clear_cache_muni(), clear_cache_tracts() and clear_cache_boundaries() to delete the cached files.

cache_dir

Character. Directory to use for cached downloads. If NULL (default), the CNEFETOOLS_CACHE_DIR environment variable is used when it is set, otherwise tools::R_user_dir() with which = "cache". Use this to point large downloads at a secondary drive or a shared volume.

verbose

Logical. Whether to print step messages and timing.

Details

Several municipalities

Pass a vector of codes to interpolate a region that spans more than one municipality in a single call. The tracts and the CNEFE points of all of them go through one allocation, each point is matched only to the tracts of its own municipality, and the result has one row per polygon, whichever municipality the polygon crosses.

Calling the function once per municipality and binding the results isn't the same. A polygon that crosses a municipal border gets, in each call, only the part of the allocation that comes from the municipality of that call. Totals (every variable except avg_inc_resp) add up, so separate outputs can be combined by summing them by polygon. avg_inc_resp can't, because it's an average over the allocated points, and two averages don't give the average of the pooled points. Use a vector of codes instead.

Large requests

Before downloading anything, the function looks up the size of each municipality's file and its number of addresses in an internal table. With verbose = TRUE, it reports how much will be downloaded and how many addresses will be processed. A warning of class cnefetools_large_request, shown even with verbose = FALSE, flags a call that processes more than 20 million addresses, or that downloads more than 1 GB. The census tract files are not counted in the download. The call still runs. To silence the warning, wrap the call in suppressWarnings(classes = "cnefetools_large_request").

Polygons at the edge of the region

Under the default scope = "muni", only the addresses and tracts of the municipalities in code_muni are used. A polygon that extends beyond them receives only the part of the allocation that comes from the municipalities requested, so its totals and avg_inc_resp describe a fraction of it. Use scope = "geom" for a complete result, which reads every municipality the polygons reach.

Municipalities detected from the polygons

With scope = "geom", the function finds the municipalities that the polygons intersect, using the 2022 IBGE municipal boundaries, and uses all of their tracts and addresses, even when they belong to different states. A message lists them, and a code_muni passed in this case is ignored.

Polygons from another source rarely follow the IBGE boundaries exactly, so a polygon along a municipal border can touch a neighboring municipality by a few meters. That neighbor is then downloaded and read too. The values are not affected, since only the points inside the polygons are aggregated, but use scope = "muni" with code_muni whenever you know which municipalities the polygons belong to, which is faster.

Value

An sf object with the user-provided polygons and the requested interpolated variables. The output CRS matches the original polygon CRS (or crs_output if specified).

Examples


# Interpolate population to user-provided polygons (neighborhoods of Lauro de Freitas-BA)
# Using geobr to download neighborhood boundaries
library(geobr)
nei_ldf <- subset(
  read_neighborhood(year = 2022),
  code_muni == 2919207
)
poly_pop <- tracts_to_polygon(
  code_muni = 2919207,
  polygon = nei_ldf,
  vars = c("pop_ph", "pop_ch"),
  cache = FALSE
)

# With scope = "geom", the municipalities the polygons intersect are used
poly_pop_geom <- tracts_to_polygon(polygon = nei_ldf, scope = "geom", cache = FALSE)



Reference table for tracts_to_* function variables

Description

A data frame that maps variable names used in tracts_to_h3() and tracts_to_polygon() to the census tract variable codes and descriptions.

Usage

tracts_variables_ref

Format

A data frame with 22 rows and 4 columns:

var_cnefetools

Variable name used in cnefetools functions.

code_var_ibge

Variable code in the census tract aggregates, as used by censobr.

desc_var_ibge

Official IBGE variable description in Portuguese.

table_ibge

Census tract table where the variable is found (Domicilios, Pessoas, or ResponsavelRenda), which correspond to the censobr datasets Domicilio, Pessoas and ResponsavelRenda.

Details

The variable codes are the ones used by the censobr package, which repackages the IBGE census tract aggregates and is where the census tract assets take their attributes from (see data-raw/sc_assets_build.R in the package repository), and each table corresponds to a censobr dataset. They don't always match the file and column names on the IBGE FTP server.

Source

IBGE - Censo Demografico 2022, Agregados por Setores Censitarios, as repackaged by the censobr package.

Examples

# View the reference table
tracts_variables_ref

# Find the IBGE code for a specific variable
tracts_variables_ref[tracts_variables_ref$var_cnefetools == "pop_ph", ]