Package {misocialr}


Title: Access the Brazilian 'MDS' Social Information Matrix ('MI Social') API from 'R'
Version: 0.4.0
Description: 'Tidyverse'-friendly interface to the 'MI Social' API of the Brazilian Ministry of Development and Social Assistance ('MDS', 'SAGI') https://aplicacoes.mds.gov.br/sagi/servicos/misocial. Retrieves monthly municipal series of the 'Cadastro Unico' (registered families and people by income bracket), the 'Bolsa Familia' programme (beneficiary families, benefits and transfers), the 'BPC' benefit, the social assistance network ('CRAS', 'CREAS' and other units), 'SUAS' funding, 'Bolsa Familia' conditionality monitoring and food security programmes as tidy long-format 'tibbles'.
License: MIT + file LICENSE
URL: https://strategicprojects.github.io/misocial/, https://github.com/StrategicProjects/misocial
BugReports: https://github.com/StrategicProjects/misocial/issues
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: httr2 (≥ 1.0.4), cli (≥ 3.6.1), tibble, purrr (≥ 1.0.0), dplyr (≥ 1.1.1), rlang, utils
Suggests: ggplot2, tidyr, scales, testthat (≥ 3.2.1), httptest2, withr, jsonlite, webfakes, knitr, rmarkdown
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-10-20 15:39:21 UTC; leite
Author: André 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: André Leite <leite@castlab.org>
Repository: CRAN
Date/Publication: 2026-10-31 11:30:07 UTC

misocialr: Access the Brazilian 'MDS' Social Information Matrix ('MI Social') API from 'R'

Description

logo

'Tidyverse'-friendly interface to the 'MI Social' API of the Brazilian Ministry of Development and Social Assistance ('MDS', 'SAGI') https://aplicacoes.mds.gov.br/sagi/servicos/misocial. Retrieves monthly municipal series of the 'Cadastro Unico' (registered families and people by income bracket), the 'Bolsa Familia' programme (beneficiary families, benefits and transfers), the 'BPC' benefit, the social assistance network ('CRAS', 'CREAS' and other units), 'SUAS' funding, 'Bolsa Familia' conditionality monitoring and food security programmes as tidy long-format 'tibbles'.

Author(s)

Maintainer: André Leite leite@castlab.org (ORCID)

Authors:

See Also

Useful links:


Convert 6-digit MDS municipality codes to 7-digit IBGE codes

Description

The MI Social API identifies municipalities by the first six digits of the IBGE code (without the check digit). This helper restores the official 7-digit code, using the IBGE check-digit rule plus the table of municipalities that are exceptions to it.

Usage

ibge_code7(x)

Arguments

x

Character or numeric vector of 6-digit codes.

Value

A character vector of 7-digit IBGE codes (NA for inputs that are not 6 digits).

Examples

ibge_code7(c(261160, "260790"))


List the fields published for one municipality

Description

Fetches the full documents of one municipality over all months (paging through the whole history) and returns the union of the field names found, with the first and last period in which each field appears. MI Social documents are sparse (a field only exists in the months it was published), which is why the whole history is scanned rather than a single document.

Usage

mds_api_fields(locality = 261160, refresh = FALSE)

Arguments

locality

6- or 7-digit IBGE code of the municipality whose history is scanned. Defaults to Recife (261160).

refresh

Logical. Ignore the cached result and ask the API again? Default FALSE.

Details

This is the catalogue of one municipality, not of the whole API: fields that exist only elsewhere (a regional CREAS, for instance) do not appear. Scan other municipalities to widen the search.

Results are cached for the session.

Value

A tibble with columns field, unit (inferred from the suffix; "unknown" when the suffix does not say), storage_type, in_dictionary, first_period and last_period. Empty, with a warning, when the API has no document for the municipality.

Examples


mds_api_fields()


Bolsa Familia programme: beneficiary families, benefits and transfers

Description

Shortcut for mds_data() with the curated Bolsa Familia fields (mds_fields("bolsa_familia")).

Usage

mds_bolsa_familia(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_bolsa_familia(periods = -6, localities = 2611606)


BPC and social assistance network (CRAS, CREAS)

Description

Shortcut for mds_data() with the curated BPC and CadSUAS fields (mds_fields("bpc_suas")).

Usage

mds_bpc_suas(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_bpc_suas(periods = 2025, localities = "PE")


Cadastro Unico: registered families and people, by income bracket

Description

Shortcut for mds_data() with the curated Cadastro Unico fields (mds_fields("cadunico")).

Usage

mds_cadunico(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_cadunico(periods = 2025, localities = "PE")


Clear the session cache

Description

Removes all cached localities, field lists, periods and field checks, forcing fresh API calls on subsequent requests. To refresh a single result, use the refresh argument of mds_periods(), mds_localities() or mds_api_fields().

Usage

mds_clear_cache()

Value

No return value, called for side effects.

Examples

mds_clear_cache()


Fetch MI Social data

Description

Main retrieval function. Returns monthly municipal values of the requested fields as a tidy long tibble: one row per field x municipality x month in which the API has a value.

Usage

mds_data(fields, periods = NULL, localities = "BR", validate = TRUE)

Arguments

fields

Character vector of field names. See mds_fields() for the curated list and mds_api_fields() for everything the API has.

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

validate

Logical. Check that fields not in the dictionary exist in the API before requesting data? Default TRUE. Local checks (names, periods, localities) always run.

Details

The query is validated before any data request (field names, period format, locality codes), then paged through Solr and, when many municipality codes are given, split into several requests whose results are bound together.

Values are returned as published. Note that the API answers 0 for months that were not published yet; use mds_drop_unpublished() to remove those trailing zeros explicitly.

Only numeric fields are supported: a field whose values are text (such as regiao) is an error rather than an empty result.

Every response is checked before it is used: a partial or malformed answer, a total that changes while paging, a document read twice, a document without municipality or month, a field with several values in one document, or two different values for the same municipality, month and field are errors (classes misocialr_error_response and misocialr_error_conflict). A requested municipality that returns no document raises a warning.

Options: misocialr.timeout (seconds per request, default 180) and misocialr.quiet (TRUE hides the progress messages).

Value

A tibble with columns locality_id (6-digit code used by the API), ibge_code (7-digit IBGE code), locality_name, state, period ("YYYYMM"), field, label, unit and value (double). The time of the request is kept in attr(x, "retrieved_at").

Examples


mds_data(
  c("bpc_ben_i", "cadsuas_qtd_cras_i"),
  periods = 2025,
  localities = c(2611606, 2607901)
)


Drop (or flag) months that were not published yet

Description

The MI Social API answers 0, not "missing", for months whose data has not been published: the BPC series, for example, carries zeros for every municipality up to December of the current year. Treating those zeros as real would make the latest months look like a collapse of the programme.

Usage

mds_drop_unpublished(
  data,
  today = Sys.Date(),
  reference = c("selection", "brazil"),
  action = c("drop", "flag")
)

Arguments

data

A tibble returned by mds_data() or a theme shortcut.

today

Reference date for rule 1. Default Sys.Date().

reference

Where the last published month is read from: "selection" or "brazil". See Details.

action

"drop" (default) removes future and unpublished rows; "flag" keeps every row and adds the columns publication_status ("published", "future", "unpublished" or "missing"), publication_reason and publication_reference.

Details

This helper applies an explicit rule, per field:

  1. months after the current month are future;

  2. months after the last month with a non-zero value are unpublished;

  3. a field with no non-zero value at all is unpublished entirely.

The "last month with a non-zero value" comes from reference:

A non-zero value in data is never classified as unpublished. If the national reference says a month with such a value is unpublished (a cached reference older than the data, for instance), the reference is requested again; if the contradiction remains, the month is kept and a warning is raised.

This is an inference from the published values, not an official publication date. A series can legitimately end in zeros, even nationally; use action = "flag" to inspect the classification before removing anything.

Rows with a missing value are never classified as zero: they are kept and flagged as "missing".

Value

data without the dropped rows, or with the classification columns. A message summarizes what was removed.

Examples

x <- tibble::tibble(
  locality_id = "261160", period = c("202506", "202507", "202508"),
  field = "bpc_ben_i", value = c(98000, 98500, 0)
)
mds_drop_unpublished(x, today = as.Date("2025-12-01"))
mds_drop_unpublished(x, today = as.Date("2025-12-01"), action = "flag")


List curated fields

Description

Returns the curated dictionary of MI Social fields: the technical field name used by the API, a readable Portuguese label, the unit and how the value is stored in the API.

Usage

mds_fields(theme = NULL)

Arguments

theme

Optional theme id (see mds_themes()). NULL (default) returns all themes.

Details

The API itself has no data dictionary. Labels are a reading of the technical names, checked against the published values; units are what is counted (Famílias, Pessoas, ⁠R$⁠, ⁠%⁠...). storage_type is the Solr type given by the suffix (⁠_i⁠ integer, ⁠_l⁠ long, ⁠_f⁠ float, ⁠_d⁠ double, ⁠_s⁠ string) and says nothing about the unit. Any other field published by the API (see mds_api_fields()) can still be requested by name in mds_data().

nature says how a field may be aggregated:

nature Across municipalities Across months
estoque (count at the month) sum do not sum
fluxo (amount in the month) sum sum
⁠fluxo anual⁠ (one value a year, in December) sum one value a year
acumulado (running total) sum do not sum
taxa, média, índice do not sum do not sum

nature_basis says where the classification comes from: medido (the monthly series was inspected: a running total only grows, an amount of the month varies and restarts), ⁠mesmo grupo de um campo medido⁠, or ⁠rótulo e unidade⁠ (inferred from the label and unit, not inspected).

Value

A tibble with columns theme, field, label, unit, nature, nature_basis and storage_type.

Examples

mds_fields("bpc_suas")


List municipalities available in the API

Description

Returns the municipalities as identified by the MI Social API, with the 6-digit code the API uses and the official 7-digit IBGE code. The list is read from one month (by default December of the last closed year), paged and checked for completeness; it is cached for the session.

Usage

mds_localities(state = NULL, period = NULL, refresh = FALSE)

Arguments

state

Optional state abbreviations (e.g. "PE") or 2-digit IBGE state codes (e.g. 26). NULL (default) returns all of Brazil.

period

Month (YYYYMM) the list is read from. NULL (default) uses December of the last closed year. The territorial division of that month is what is returned.

refresh

Logical. Ignore the cached list and ask the API again? Default FALSE.

Value

A tibble with columns locality_id (6 digits, as in the API), ibge_code (7 digits), locality_name, state and region. The month and time of the request are kept in attr(x, "period") and attr(x, "retrieved_at").

Examples


mds_localities("PE")


Bolsa Familia conditionalities: education and health follow-up

Description

Shortcut for mds_data() with the curated conditionality fields (mds_fields("pbf_condicionalidades")): the SICON series from 2023 on (education, health, warnings, blocks, suspensions and cancellations) and the IGD-M follow-up rates, available since 2015.

Usage

mds_pbf_condicionalidades(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_pbf_condicionalidades(periods = 2026, localities = "PE")


List the periods available for a field

Description

Uses Solr facets to count, for each month, how many municipalities have a value for the field and how many of those values are non-zero.

Usage

mds_periods(field, localities = "BR", refresh = FALSE)

Arguments

field

A single field name (see mds_fields()).

localities

Localities to restrict the count to; same forms as in mds_data(). Default "BR".

refresh

Logical. Ignore the cached result and ask the API again? Default FALSE.

Details

The second count matters: the API returns 0 for months that have not been published yet (for instance, the BPC series carries zeros for every municipality up to the end of the current year). A month where n_nonzero is 0 for the whole selection is almost always unpublished, not a true zero. See mds_drop_unpublished().

Results are cached for the session. Large selections are counted in blocks of at most 200 municipality codes (the same split as mds_data()); the blocks do not overlap, so their counts are summed.

Value

A tibble with columns period ("YYYYMM"), n_localities and n_nonzero, ordered by period. The time of the request is kept in attr(x, "retrieved_at").

Examples


mds_periods("bpc_ben_i", localities = "PE")


Food and nutrition security: PAA, Fomento Rural and cisterns

Description

Shortcut for mds_data() with the curated food security fields (mds_fields("seguranca_alimentar")). Cistern counts are cumulative.

Usage

mds_seguranca_alimentar(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_seguranca_alimentar(periods = 2025, localities = "PE")


SUAS funding: FNAS transfers, account balances and IGD-M

Description

Shortcut for mds_data() with the curated funding fields (mds_fields("suas_financiamento")).

Usage

mds_suas_financiamento(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Details

The transfer components add up to suas_repasse_mun_vl_total_fundo_f (checked for Pernambuco in 06/2026 and 09/2026). The account balances do not add up to the general total, so they should be read one by one.

Value

A tibble in the format of mds_data().

Examples


mds_suas_financiamento(periods = 2025, localities = 2611606)


Social assistance network (CadSUAS)

Description

Shortcut for mds_data() with the curated network fields (mds_fields("suas_rede")): CRAS, CREAS, Centro POP, centros de convivencia, centros-dia, unidades de acolhimento, regional CREAS and the professionals registered in each kind of unit (professionals only from 09/2025).

Usage

mds_suas_rede(periods = NULL, localities = "BR", fields = NULL)

Arguments

periods

Periods to fetch:

  • NULL (default): the last 12 months up to the current month;

  • a negative number -n: the last n months up to the current month;

  • years (2024) and/or months as YYYYMM (202401, "202401").

localities

"BR" (all of Brazil), state abbreviations ("PE") or 2-digit state codes (26), and/or 6- or 7-digit IBGE municipality codes (2611606), in any combination. Default "BR".

fields

Fields to fetch. NULL (default) fetches every curated field of the theme.

Value

A tibble in the format of mds_data().

Examples


mds_suas_rede(periods = 202609, localities = "PE")


List the themes covered by the package

Description

Each theme groups a curated set of MI Social fields (see mds_fields()) and has a shortcut retrieval function: mds_cadunico(), mds_bolsa_familia(), mds_bpc_suas(), mds_suas_rede(), mds_suas_financiamento(), mds_pbf_condicionalidades() and mds_seguranca_alimentar().

Usage

mds_themes()

Value

A tibble with columns theme, name, description and n_fields.

Examples

mds_themes()