Reads a Stata .dta file and integrates with mariposa's tagged NA system.
Handles two scenarios:
Native extended missing values (
.athrough.z): Automatically detected and annotated.Numeric missing codes (e.g., -9, -42): When
tag_nais provided, these regular values are converted to tagged NAs, giving the same result asread_spss()withtag_na = TRUE.
Arguments
- path
Path to a Stata
.dtafile.- 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.
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 codesis.na()returnsTRUEfor these values (standard R behavior)
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
# \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)
}
#> ✔ Wrote 16 variables (2500 obs.) to file18f62439fe9e.dta
# }
