Package {electedBR}


Title: Brazilian Election Winners and Sitting Members of Congress
Version: 0.1.0
Description: Retrieves the candidates elected in Brazilian municipal and general elections since 2018, consolidated from the open data of the Superior Electoral Court (TSE, https://dadosabertos.tse.jus.br/) and distributed as yearly Parquet files, together with the federal deputies and senators currently serving according to the open data APIs of the Chamber of Deputies (https://dadosabertos.camara.leg.br/) and the Federal Senate (https://www12.senado.leg.br/dados-abertos). Election results and current office holding are kept as distinct queries; electoral roles, service history and provenance are preserved. Every function returns a tibble with English column names and has a Portuguese alias.
License: GPL-3
URL: https://github.com/StrategicProjects/electedBR, https://strategicprojects.github.io/electedBR/
BugReports: https://github.com/StrategicProjects/electedBR/issues
Encoding: UTF-8
Language: en-US
LazyData: true
Depends: R (≥ 4.1.0)
Imports: dplyr (≥ 1.1.0), httr2 (≥ 1.0.0), nanoparquet, rlang, tibble, tools, utils
Suggests: knitr, rmarkdown, testthat (≥ 3.0.0), withr
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-09-25 21:57:03 UTC; leite
Author: Andre Leite ORCID iD [aut, cre], Marcos Wasiliew ORCID iD [aut], Hugo Vasconcelos ORCID iD [aut], Carlos Amorim ORCID iD [aut], Diogo Bezerra ORCID iD [aut]
Maintainer: Andre Leite <leite@castlab.org>
Repository: CRAN
Date/Publication: 2026-10-06 15:20:02 UTC

electedBR: Brazilian Election Winners and Sitting Members of Congress

Description

logo

Retrieves the candidates elected in Brazilian municipal and general elections since 2018, consolidated from the open data of the Superior Electoral Court (TSE, https://dadosabertos.tse.jus.br/) and distributed as yearly Parquet files, together with the federal deputies and senators currently serving according to the open data APIs of the Chamber of Deputies (https://dadosabertos.camara.leg.br/) and the Federal Senate (https://www12.senado.leg.br/dados-abertos). Election results and current office holding are kept as distinct queries; electoral roles, service history and provenance are preserved. Every function returns a tibble with English column names and has a Portuguese alias.

Author(s)

Maintainer: Andre Leite leite@castlab.org (ORCID)

Authors:

See Also

Useful links:


Cache directory

Description

Directory where the yearly election files, the parliamentary tables and their snapshots are stored. By default it is a folder under the session's tempdir(), so nothing persists between sessions and nothing is written outside the temporary directory unless you opt in. To keep the files between sessions, set the environment variable ELECTEDBR_CACHE_DIR or the option electedBR.cache_dir (for example to tools::R_user_dir("electedBR", "cache")), or pass cache_dir to each function. The precedence is: the cache_dir argument, then the environment variable, then the option, then tempdir().

Usage

elected_cache_dir(path = NULL)

diretorio_cache_eleitos(caminho = NULL)

Arguments

path

Optional directory; when given, it is returned (created if needed) instead of the default resolution.

caminho

Portuguese alias of path.

Details

The parliamentary functions also keep a snapshot of every completed collection under ⁠cache_dir/snapshots/⁠; with a persistent cache these accumulate and can be removed with elected_clear_cache().

Value

The cache directory path, created if needed, invisibly.

Examples

elected_cache_dir()
old <- Sys.getenv("ELECTEDBR_CACHE_DIR", unset = NA)
Sys.setenv(ELECTEDBR_CACHE_DIR = file.path(tempdir(), "electedBR-persistent"))
elected_cache_dir()
if (is.na(old)) Sys.unsetenv("ELECTEDBR_CACHE_DIR") else
  Sys.setenv(ELECTEDBR_CACHE_DIR = old)

Remove cached files

Description

Deletes the yearly election files, the cached parliamentary tables and the snapshots stored in cache_dir. The next query downloads them again.

Usage

elected_clear_cache(cache_dir = elected_cache_dir())

limpar_cache_eleitos(cache_dir = elected_cache_dir())

Arguments

cache_dir

Cache directory; see elected_cache_dir().

Value

The number of files removed, invisibly.

Examples

dir <- file.path(tempdir(), "electedBR-example")
dir.create(dir)
writeLines("x", file.path(dir, "elected_2024.parquet"))
elected_clear_cache(dir)

Yearly files of elected candidates

Description

Index of the Parquet files distributed by the package, one per election year, with the URL they are downloaded from and the checksums used to verify the download. Used internally by get_elected(); the host can be overridden with the electedBR.base_url option or the base_url argument.

Usage

elected_years

Format

A data frame with one row per year and the columns:

year

Election year.

kind

"municipal" (mayors, deputy mayors and councilors) or "general" (senators and federal, state and district deputies).

file

File name (for example elected_2024.parquet).

url

Download URL of the file.

bytes

File size in bytes, used to check the download.

md5

MD5 checksum of the file.

rows

Number of rows (elected candidates plus alternates).

built

Date on which the file was generated from the TSE data.

Details

Each file is the output of normalize_elected() with include_alternates = TRUE applied to the TSE votação nominal por município e zona dataset of that year, so it holds both the elected candidates and the alternates classified in the TSE file.

Source

Derived from the TSE open data portal, https://dadosabertos.tse.jus.br/; files hosted at https://huggingface.co/datasets/mlkwy/electedBR.

Examples

elected_years

Federal deputies and senators currently serving

Description

Retrieves the members of the Chamber of Deputies and of the Federal Senate currently in service, from the open data APIs of each house. The lists include alternates who are serving; mandate_role tells principals and alternates apart, independently of the service status. Election results are a different question, answered by get_elected().

Usage

get_deputies(
  state = NULL,
  party = NULL,
  status = "serving",
  role = NULL,
  refresh = FALSE,
  max_age_hours = 6,
  cache_dir = elected_cache_dir()
)

get_senators(
  state = NULL,
  party = NULL,
  status = "serving",
  role = NULL,
  refresh = FALSE,
  max_age_hours = 6,
  cache_dir = elected_cache_dir()
)

consultar_deputados(
  uf = NULL,
  partido = NULL,
  situacao = "em_exercicio",
  condicao = NULL,
  atualizar = FALSE,
  validade_horas = 6,
  cache_dir = elected_cache_dir()
)

consultar_senadores(
  uf = NULL,
  partido = NULL,
  situacao = "em_exercicio",
  condicao = NULL,
  atualizar = FALSE,
  validade_horas = 6,
  cache_dir = elected_cache_dir()
)

Arguments

state

Two-letter state abbreviations; NULL keeps every state.

party

Party abbreviations (current affiliation).

status

Only "serving" is supported.

role

NULL, or one or more of "principal", "alternate" and "unknown".

refresh

Logical. Collect again even if a fresh cache exists.

max_age_hours

Maximum age of the cache, in hours (default six).

cache_dir

Cache directory; see elected_cache_dir().

uf, partido, situacao, condicao, atualizar, validade_horas

Portuguese aliases of state, party, status ("em_exercicio"), role ("titular", "suplente", "desconhecido"), refresh and max_age_hours.

Details

The Chamber list is paginated and the electoral condition of each deputy comes from a detail request per deputy, so the first call without state issues several hundred requests; results are cached for max_age_hours hours in cache_dir, and every completed collection is also kept as an immutable snapshot under ⁠cache_dir/snapshots/⁠. A network or schema failure raises an error rather than silently returning expired data.

Value

A tibble with the columns person_id, source_id, name, state, office, current_party, mandate_id, mandate_role, mandate_role_raw, exercise_status, exercise_status_raw, exercise_start, exercise_end, status_recorded_at, source_updated_at, source, reference and retrieved_at. Columns ending in ⁠_raw⁠ keep the label used by the source; person_id is namespaced (camara:204379, senado:5322) and is not a TSE identifier.

See Also

get_service_history() for the status records and service periods of one member.

Examples


get_senators(state = "PE", cache_dir = tempdir())
get_deputies(state = c("PE", "PB"), role = "alternate", cache_dir = tempdir())
consultar_senadores(uf = "PE", cache_dir = tempdir())


Candidates elected in Brazilian elections

Description

Returns the candidates elected (and optionally the alternates) in a Brazilian election year, from the yearly files derived from the TSE open data and hosted by the package (see elected_years). Municipal offices (mayor, vice mayor, councilor) are available for municipal election years (2020, 2024, ...) and president, vice president, governors, vice governors, senators and federal, state and district deputies for general election years (2018, 2022, ...).

Usage

get_elected(
  year = 2024L,
  state = NULL,
  municipality = NULL,
  office = NULL,
  party = NULL,
  include_alternates = FALSE,
  cache_dir = elected_cache_dir(),
  refresh = FALSE,
  as_of = NULL,
  events = NULL,
  base_url = getOption("electedBR.base_url")
)

get_mayors(
  year = 2024L,
  state = NULL,
  municipality = NULL,
  party = NULL,
  cache_dir = elected_cache_dir(),
  refresh = FALSE,
  as_of = NULL,
  events = NULL,
  base_url = getOption("electedBR.base_url")
)

get_councilors(
  year = 2024L,
  state = NULL,
  municipality = NULL,
  party = NULL,
  include_alternates = FALSE,
  cache_dir = elected_cache_dir(),
  refresh = FALSE,
  base_url = getOption("electedBR.base_url")
)

consultar_eleitos(
  ano = 2024L,
  uf = NULL,
  municipio = NULL,
  cargo = NULL,
  partido = NULL,
  incluir_suplentes = FALSE,
  cache_dir = elected_cache_dir(),
  atualizar = FALSE,
  data_referencia = NULL,
  eventos = NULL,
  base_url = getOption("electedBR.base_url")
)

consultar_prefeitos(
  ano = 2024L,
  uf = NULL,
  municipio = NULL,
  partido = NULL,
  cache_dir = elected_cache_dir(),
  atualizar = FALSE,
  data_referencia = NULL,
  eventos = NULL,
  base_url = getOption("electedBR.base_url")
)

consultar_vereadores(
  ano = 2024L,
  uf = NULL,
  municipio = NULL,
  partido = NULL,
  incluir_suplentes = FALSE,
  cache_dir = elected_cache_dir(),
  atualizar = FALSE,
  base_url = getOption("electedBR.base_url")
)

Arguments

year

Election year; one of elected_years$year.

state

One or more two-letter state abbreviations ("PE", "SP"). NULL (the default) keeps every state. President and vice president rows carry no state and are dropped when state is given.

municipality

Municipality names (matched exactly, ignoring accents and case) or TSE municipality codes (not IBGE codes). Municipal offices only.

office

One or more of "president", "vice_president", "governor", "vice_governor", "senator", "federal_deputy", "state_deputy", "district_deputy", "mayor", "vice_mayor" and "councilor". NULL keeps every office in the year. Running mates come from the TSE candidates file, have votes = NA and are linked to the head of their ticket by ticket_candidate_id.

party

Party abbreviations at the time of the election.

include_alternates

Logical. Also return the candidates classified as SUPLENTE (alternate) in the TSE file. This is the classification at the poll, not a current substitution queue.

cache_dir

Directory where the yearly files are stored; see elected_cache_dir(). By default a folder under tempdir(), so set the option or environment variable described there to keep files between sessions.

refresh

Logical. Download the file again even if a copy is cached.

as_of

Optional date (or string convertible with as.Date()). When given, the office-holding events dated on or before it are applied and the columns status_as_of, status_date, office_as_of and status_source are added: status_as_of is the latest event recorded for the official (resignation, death, removal, leave, return), succession for a running mate who took over (with office_as_of set to the office assumed) or no_change_recorded.

events

Optional events table with the columns of get_officeholding_events(), used instead of downloading it.

base_url

Optional base URL of a mirror hosting the files listed in elected_years. Defaults to getOption("electedBR.base_url"); when NULL, the url column of elected_years is used.

ano, uf, municipio, cargo, partido, incluir_suplentes, atualizar, data_referencia, eventos

Portuguese aliases of year, state, municipality, office, party, include_alternates, refresh, as_of and events. cargo also accepts the Portuguese labels "PRESIDENTE", "VICE-PRESIDENTE", "GOVERNADOR", "VICE-GOVERNADOR", "SENADOR", "DEPUTADO FEDERAL", "DEPUTADO ESTADUAL", "DEPUTADO DISTRITAL", "PREFEITO", "VICE-PREFEITO" and "VEREADOR".

Details

The first call for a year downloads its Parquet file (about 1 MB for a general election, up to 25 MB for a municipal one, see elected_years$bytes) into cache_dir; later calls read the local copy. The default cache lives under tempdir(); see elected_cache_dir() to make it persistent. Results describe who was elected in the poll: they do not establish who currently holds office nor current party membership. For sitting members of Congress use get_deputies() and get_senators(); for mayors and governors, as_of applies the curated get_officeholding_events() table (resignations, deaths, removals, leaves and successions), which records changes but does not prove that an official without a record is in office.

Value

A tibble with the columns documented in normalize_elected(): year, election_id, round, state, municipality_tse_id, municipality, office, candidate_id, ticket_candidate_id, name, ballot_name, party_at_election, election_status, votes and reference, plus the four ⁠*_as_of⁠ columns when as_of is given. An empty tibble with the same columns is returned when no row matches. The attributes source (TSE dataset page) and notice are set.

See Also

get_mayors(), get_councilors(), elected_years, get_officeholding_events(), elected_clear_cache().

Examples


# Mayors elected in Pernambuco in 2024
get_mayors(state = "PE", municipality = c("Recife", "Caruaru"),
           cache_dir = tempdir())

# Federal deputies elected in 2022, including alternates
get_elected(2022, state = "PE", office = "federal_deputy",
            include_alternates = TRUE, cache_dir = tempdir())

# Governor and vice governor of Pernambuco elected in 2022
get_elected(2022, state = "PE", office = c("governor", "vice_governor"),
            cache_dir = tempdir())

# Who holds the Recife mayoralty on a given date, after the 2026 resignation
get_mayors(state = "PE", municipality = "Recife", as_of = "2026-06-01",
           cache_dir = tempdir())

# Same query through the Portuguese alias
consultar_eleitos(2022, uf = "PE", cargo = "DEPUTADO FEDERAL",
                  cache_dir = tempdir())


Office-holding events for elected officials

Description

A curated table of changes in office holding after the election (an official who resigned, died, was removed or took leave, and who succeeded them), for the offices covered by get_elected() that have no official API of sitting members: mayors, governors and their deputies. It is maintained in the package repository, served from the same host as the yearly files and refreshed on demand, not on a schedule; an official absent from the table has simply not been recorded, which is not evidence of being in office. Every row cites its source. Contributions are welcome at https://github.com/StrategicProjects/electedBR.

Usage

get_officeholding_events(
  events = NULL,
  refresh = FALSE,
  max_age_hours = 24,
  cache_dir = elected_cache_dir(),
  base_url = getOption("electedBR.base_url")
)

consultar_eventos_exercicio(
  eventos = NULL,
  atualizar = FALSE,
  validade_horas = 24,
  cache_dir = elected_cache_dir(),
  base_url = getOption("electedBR.base_url")
)

Arguments

events

Optional data frame with the same columns, used instead of downloading (for example a local copy under review).

refresh

Logical. Collect again even if a fresh cache exists.

max_age_hours

Maximum age of the cache, in hours (default six).

cache_dir

Cache directory; see elected_cache_dir().

base_url

Optional base URL of a mirror hosting the files listed in elected_years. Defaults to getOption("electedBR.base_url"); when NULL, the url column of elected_years is used.

eventos, atualizar, validade_horas

Portuguese aliases of events, refresh and max_age_hours.

Value

A tibble with the columns year and candidate_id (identifying the official in the yearly file of that election), name, office, state, municipality_tse_id, event (resignation, death, removal, leave or return), date, successor_candidate_id, successor_name, successor_date (when the successor took office), source (URL of an official or press record) and notes, plus retrieved_at.

See Also

get_elected(), whose as_of argument applies these events.

Examples


get_officeholding_events(cache_dir = tempdir())


Service history of a deputy or senator

Description

Returns the official records about the service of one member of Congress, identified by the person_id returned by get_deputies() or get_senators(). The two houses publish different things and the difference is preserved rather than reconciled:

Usage

get_service_history(
  person_id,
  refresh = FALSE,
  max_age_hours = 6,
  cache_dir = elected_cache_dir()
)

consultar_historico_exercicio(
  id_pessoa,
  atualizar = FALSE,
  validade_horas = 6,
  cache_dir = elected_cache_dir()
)

Arguments

person_id

A single id such as "camara:204379" or "senado:5322".

refresh

Logical. Collect again even if a fresh cache exists.

max_age_hours

Maximum age of the cache, in hours (default six).

cache_dir

Cache directory; see elected_cache_dir().

id_pessoa, atualizar, validade_horas

Portuguese aliases of person_id, refresh and max_age_hours.

Details

Value

A tibble with the columns person_id, name, state, office, mandate_id, mandate_role, mandate_role_raw, exercise_status, exercise_status_raw, party_at_record, record_type, record_at, exercise_start, exercise_end, description, source, source_updated_at and retrieved_at.

Examples


senators <- get_senators(state = "PE", cache_dir = tempdir())
get_service_history(senators$person_id[[1]], cache_dir = tempdir())
get_service_history("camara:204379", cache_dir = tempdir())


Consolidate TSE files into the candidates elected

Description

Turns the raw votação nominal por município e zona table published by the Superior Electoral Court (TSE) into one row per elected candidate. Votes are summed over electoral zones (over municipalities for statewide offices and over the whole country for president), the last round available for each candidate is kept, and distinct elections held on the same date (for instance ordinary and supplementary polls, which have different CD_ELEICAO codes) are never merged.

Usage

normalize_elected(data, candidates = NULL, include_alternates = FALSE)

normalizar_eleitos(dados, candidatos = NULL, incluir_suplentes = FALSE)

Arguments

data

A data frame with the TSE vote-by-municipality-and-zone layout. The columns ANO_ELEICAO, CD_ELEICAO, NR_TURNO, SG_UF, CD_MUNICIPIO, NM_MUNICIPIO, CD_CARGO, DS_CARGO, SQ_CANDIDATO, NM_CANDIDATO, NM_URNA_CANDIDATO, SG_PARTIDO, DS_SIT_TOT_TURNO and QT_VOTOS_NOMINAIS are required (case-insensitive).

candidates

Optional data frame with the TSE candidates layout (consulta_cand), used to add the elected running mates. The columns ANO_ELEICAO, CD_ELEICAO, NR_TURNO, SG_UF, SG_UE, NM_UE, CD_CARGO, SQ_CANDIDATO, NR_CANDIDATO, NM_CANDIDATO, NM_URNA_CANDIDATO, SG_PARTIDO and DS_SIT_TOT_TURNO are required.

include_alternates

Logical. Also keep candidates whose final status is SUPLENTE (alternate) in the TSE file. Senate ticket alternates have no votes of their own and are not covered; see get_senators() for the alternates currently serving.

dados, candidatos, incluir_suplentes

Portuguese aliases of data, candidates and include_alternates.

Details

Running mates (vice president, vice governors and vice mayors) receive no votes of their own and are absent from the vote files. When the TSE candidatos table of the same year is given in candidates, the running mates classified as elected are added with votes = NA and ticket_candidate_id pointing to the head of their ticket (same NR_CANDIDATO in the same election and electoral unit).

This is the function that builds the yearly files distributed with the package; it is exported so that the same rules can be applied to a fresh TSE download (for example the output of electionsBR::elections_tse()).

Value

A tibble with one row per candidate and election, with the columns year, election_id, round, state, municipality_tse_id, municipality, office, candidate_id, ticket_candidate_id, name, ballot_name, party_at_election, election_status, votes and reference. office is one of president, vice_president, governor, vice_governor, senator, federal_deputy, state_deputy, district_deputy, mayor, vice_mayor or councilor. For statewide offices municipality_tse_id and municipality are NA; for president and vice president state is NA as well. ticket_candidate_id is NA except for running mates, and votes is NA for running mates.

See Also

get_elected() for the ready-made yearly files.

Examples

votes <- data.frame(
  ANO_ELEICAO = 2024, CD_ELEICAO = "619", NR_TURNO = 1, SG_UF = "PE",
  CD_MUNICIPIO = "25313", NM_MUNICIPIO = "RECIFE", CD_CARGO = "13",
  DS_CARGO = "Vereador", SQ_CANDIDATO = c("1", "1", "2"),
  NM_CANDIDATO = c("ANA", "ANA", "BRUNO"),
  NM_URNA_CANDIDATO = c("ANA", "ANA", "BRUNO"),
  SG_PARTIDO = c("PSB", "PSB", "PT"),
  DS_SIT_TOT_TURNO = c("ELEITO POR QP", "ELEITO POR QP", "SUPLENTE"),
  QT_VOTOS_NOMINAIS = c(100, 50, 200)
)
normalize_elected(votes)
normalize_elected(votes, include_alternates = TRUE)