Learn R Programming

mariposa (version 0.7.3)

read_stata: Read Stata Data with Tagged Missing Values

Description

Reads a Stata .dta file and integrates with mariposa's tagged NA system. Handles two scenarios:

  1. Native extended missing values (.a through .z): Automatically detected and annotated.

  2. Numeric missing codes (e.g., -9, -42): When tag_na is provided, these regular values are converted to tagged NAs, giving the same result as read_spss() with tag_na = TRUE.

Usage

read_stata(path, encoding = NULL, tag_na = NULL, verbose = FALSE)

Value

A tibble with the Stata data. Variables with missing value codes have:

  • Tagged NAs for each missing type

  • An "na_tag_map" attribute mapping tag characters to original codes

  • is.na() returns TRUE for these values (standard R behavior)

Arguments

path

Path to a Stata .dta file.

encoding

Character encoding for the file. If NULL, haven's default encoding detection is used. Generally only needed for Stata 13 files and earlier.

tag_na

Numeric vector of values to treat as missing (e.g., c(-9, -8, -42)). These values will be converted to tagged NAs across all numeric variables. Use this when Stata files contain SPSS-style missing codes stored as regular values. Default: NULL (only detect native Stata extended missing values).

verbose

If TRUE, prints a message summarizing how many variables contain tagged missing values.

Details

Native Extended Missing Values

Stata supports 27 distinct missing value types: . (system missing) and .a through .z (extended missing values). The haven package preserves these as tagged NAs automatically. read_stata() adds the na_tag_map attribute so that mariposa's tagged NA functions work seamlessly.

Numeric Missing Codes (tag_na)

Many Stata files -- especially those converted from SPSS -- store missing value codes as regular numeric values (e.g., -9 = "No answer", -42 = "Data error"). The tag_na parameter converts these to tagged NAs, enabling proper handling in frequency(), codebook(), and other functions.

When tag_na is used, untag_na() can recover the original numeric codes.

See Also

na_frequencies(), strip_tags(), untag_na(), read_spss(), read_sas(), read_xpt(), haven::read_dta()

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples

Run this code
# \donttest{
if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip through a temporary .dta file (with your own data,
  # simply pass its path instead)
  tmp <- tempfile(fileext = ".dta")
  write_stata(survey_data, tmp)
  data <- read_stata(tmp)

  # Read with SPSS-style missing codes tagged as distinct NA types
  data <- read_stata(tmp, tag_na = c(-9, -8))

  # frequency() shows each missing type separately
  data |> frequency(income)

  unlink(tmp)
}
# }

Run the code above in your browser using DataLab