| Title: | Import and Export 'SPSS', 'Stata' and 'SAS' Files |
|---|---|
| Description: | Import foreign statistical formats into R via the embedded 'ReadStat' C library, <https://github.com/WizardMac/ReadStat>. |
| Authors: | Hadley Wickham [aut, cre], Evan Miller [aut, cph] (Author of included ReadStat code), Danny Smith [aut], Posit Software, PBC [cph, fnd] |
| Maintainer: | Hadley Wickham <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 2.5.5.9000 |
| Built: | 2026-10-22 00:11:29 UTC |
| Source: | https://github.com/tidyverse/haven |
The base function as.factor() is not a generic, but forcats::as_factor()
is. haven provides as_factor() methods for labelled() and
labelled_spss() vectors, and data frames. By default, when applied to a
data frame, it only affects labelled columns.
## S3 method for class 'data.frame' as_factor(x, ..., only_labelled = TRUE) ## S3 method for class 'haven_labelled' as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... ) ## S3 method for class 'labelled' as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... )## S3 method for class 'data.frame' as_factor(x, ..., only_labelled = TRUE) ## S3 method for class 'haven_labelled' as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... ) ## S3 method for class 'labelled' as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... )
x |
Object to coerce to a factor. |
... |
Other arguments passed down to method. |
only_labelled |
Only apply to labelled columns? |
levels |
How to create the levels of the generated factor:
|
ordered |
If |
Includes methods for both class haven_labelled and labelled
for backward compatibility.
x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)) # Default method uses values where available as_factor(x) # You can also extract just the labels as_factor(x, levels = "labels") # Or just the values as_factor(x, levels = "values") # Or combine value and label as_factor(x, levels = "both") # as_factor() will preserve SPSS missing values from values and ranges y <- labelled_spss(1:10, na_values = c(2, 4), na_range = c(8, 10)) as_factor(y) # use zap_missing() first to convert to NAs zap_missing(y) as_factor(zap_missing(y))x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)) # Default method uses values where available as_factor(x) # You can also extract just the labels as_factor(x, levels = "labels") # Or just the values as_factor(x, levels = "values") # Or combine value and label as_factor(x, levels = "both") # as_factor() will preserve SPSS missing values from values and ranges y <- labelled_spss(1:10, na_values = c(2, 4), na_range = c(8, 10)) as_factor(y) # use zap_missing() first to convert to NAs zap_missing(y) as_factor(zap_missing(y))
A labelled vector is a common data structure in other statistical
environments, allowing you to assign text labels to specific values.
This class makes it possible to import such labelled vectors in to R
without loss of fidelity. This class provides few methods, as I
expect you'll coerce to a standard R class (e.g. a factor())
soon after importing.
labelled(x = double(), labels = NULL, label = NULL) is.labelled(x)labelled(x = double(), labels = NULL, label = NULL) is.labelled(x)
x |
A vector to label. Must be either numeric (integer or double) or character. |
labels |
A named vector or |
label |
A short, human-readable description of the vector. |
s1 <- labelled(c("M", "M", "F"), c(Male = "M", Female = "F")) s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2)) s3 <- labelled( c(1, 1, 2), c(Male = 1, Female = 2), label = "Assigned sex at birth" ) # Unfortunately it's not possible to make as.factor work for labelled objects # so instead use as_factor. This works for all types of labelled vectors. as_factor(s1) as_factor(s1, levels = "values") as_factor(s2) # Other statistical software supports multiple types of missing values s3 <- labelled( c("M", "M", "F", "X", "N/A"), c(Male = "M", Female = "F", Refused = "X", "Not applicable" = "N/A") ) s3 as_factor(s3) # Often when you have a partially labelled numeric vector, labelled values # are special types of missing. Use zap_labels to replace labels with missing # values x <- labelled(c(1, 2, 1, 2, 10, 9), c(Unknown = 9, Refused = 10)) zap_labels(x)s1 <- labelled(c("M", "M", "F"), c(Male = "M", Female = "F")) s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2)) s3 <- labelled( c(1, 1, 2), c(Male = 1, Female = 2), label = "Assigned sex at birth" ) # Unfortunately it's not possible to make as.factor work for labelled objects # so instead use as_factor. This works for all types of labelled vectors. as_factor(s1) as_factor(s1, levels = "values") as_factor(s2) # Other statistical software supports multiple types of missing values s3 <- labelled( c("M", "M", "F", "X", "N/A"), c(Male = "M", Female = "F", Refused = "X", "Not applicable" = "N/A") ) s3 as_factor(s3) # Often when you have a partially labelled numeric vector, labelled values # are special types of missing. Use zap_labels to replace labels with missing # values x <- labelled(c(1, 2, 1, 2, 10, 9), c(Unknown = 9, Refused = 10)) zap_labels(x)
This class is only used when user_na = TRUE in
read_sav(). It is similar to the labelled() class
but it also models SPSS's user-defined missings, which can be up to
three distinct values, or for numeric vectors a range.
labelled_spss( x = double(), labels = NULL, na_values = NULL, na_range = NULL, label = NULL )labelled_spss( x = double(), labels = NULL, na_values = NULL, na_range = NULL, label = NULL )
x |
A vector to label. Must be either numeric (integer or double) or character. |
labels |
A named vector or |
na_values |
A vector of values that should also be considered as missing. |
na_range |
A numeric vector of length two giving the (inclusive) extents
of the range. Use |
label |
A short, human-readable description of the vector. |
x1 <- labelled_spss(1:10, c(Good = 1, Bad = 8), na_values = c(9, 10)) is.na(x1) x2 <- labelled_spss( 1:10, c(Good = 1, Bad = 8), na_range = c(9, Inf), label = "Quality rating" ) is.na(x2) # Print data and metadata x2x1 <- labelled_spss(1:10, c(Good = 1, Bad = 8), na_values = c(9, 10)) is.na(x1) x2 <- labelled_spss( 1:10, c(Good = 1, Bad = 8), na_range = c(9, Inf), label = "Quality rating" ) is.na(x2) # Print data and metadata x2
meta() gets and sets the metadata attached to a vector or data frame
by read_sas(), read_spss(), or read_stata(). The metadata is stored
in a single haven_meta attribute holding an S7 object whose class
depends on the vendor and on whether x is a data frame:
Column metadata: meta_var_sas, meta_var_spss, meta_var_stata.
Data frame metadata: meta_df_sas, meta_df_spss, meta_df_stata.
If no metadata has been set, meta() falls back to the legacy
format.*, display_width, width, notes, and *_timestamp
attributes, so objects saved by older versions of haven keep working.
meta(x, vendor = NULL) meta(x, vendor = NULL) <- valuemeta(x, vendor = NULL) meta(x, vendor = NULL) <- value
x |
A vector or data frame. |
vendor |
If supplied, one of |
value |
|
meta() returns an S7 object inheriting from meta_var (for
vectors) or meta_df (for data frames), or NULL.
df <- read_sav(system.file("examples", "iris.sav", package = "haven")) # Data frame metadata meta(df) meta(df)@created # Column metadata meta(df$Species) meta(df$Species)@format # Modify metadata meta(df$Species)@measure <- "ordinal" meta(df$Species)df <- read_sav(system.file("examples", "iris.sav", package = "haven")) # Data frame metadata meta(df) meta(df)@created # Column metadata meta(df$Species) meta(df$Species)@format # Modify metadata meta(df$Species)@measure <- "ordinal" meta(df$Species)
meta_var_sas (column) and meta_df_sas (data frame) hold
metadata read from and written to SAS files. See meta() for how to
access them.
meta_var_sas(format = NULL, informat = NULL, width = NULL) meta_df_sas( created = NULL, modified = NULL, table_name = NULL, xpt_version = NULL )meta_var_sas(format = NULL, informat = NULL, width = NULL) meta_df_sas( created = NULL, modified = NULL, table_name = NULL, xpt_version = NULL )
format |
The display format (e.g. |
informat |
The input format. |
width |
The variable width. |
created, modified
|
File creation and modification timestamps. |
table_name |
The SAS table name. |
xpt_version |
The transport file version (5 or 8). |
df <- read_sas(system.file("examples", "iris.sas7bdat", package = "haven")) meta(df) meta(df)@table_name meta(df$Species) meta(df$Species)@formatdf <- read_sas(system.file("examples", "iris.sas7bdat", package = "haven")) meta(df) meta(df)@table_name meta(df$Species) meta(df$Species)@format
meta_var_spss (column) and meta_df_spss (data frame) hold
metadata read from and written to SPSS files. See meta() for how to
access them.
meta_var_spss( format = NULL, display_width = NULL, width = NULL, measure = NULL, alignment = NULL ) meta_df_spss(created = NULL, modified = NULL, notes = NULL, mr_sets = NULL)meta_var_spss( format = NULL, display_width = NULL, width = NULL, measure = NULL, alignment = NULL ) meta_df_spss(created = NULL, modified = NULL, notes = NULL, mr_sets = NULL)
format |
The display format. |
display_width |
The display width. |
width |
The variable width. |
measure |
The measure level: |
alignment |
The display alignment: |
created, modified
|
File creation and modification timestamps. |
notes |
File notes. |
mr_sets |
Multiple response sets. |
df <- read_sav(system.file("examples", "iris.sav", package = "haven")) meta(df) meta(df)@created meta(df$Species) meta(df$Species)@measuredf <- read_sav(system.file("examples", "iris.sav", package = "haven")) meta(df) meta(df)@created meta(df$Species) meta(df$Species)@measure
meta_var_stata (column) and meta_df_stata (data frame) hold
metadata read from and written to Stata files. See meta() for how to
access them.
meta_var_stata(format = NULL, type = NULL) meta_df_stata(created = NULL, modified = NULL, notes = NULL, version = NULL)meta_var_stata(format = NULL, type = NULL) meta_df_stata(created = NULL, modified = NULL, notes = NULL, version = NULL)
format |
The display format. |
type |
The storage type: |
created, modified
|
File creation and modification timestamps. |
notes |
File notes. |
version |
The Stata file version. |
df <- read_dta(system.file("examples", "iris.dta", package = "haven")) meta(df) meta(df)@version meta(df$species) meta(df$species)@formatdf <- read_dta(system.file("examples", "iris.dta", package = "haven")) meta(df) meta(df)@version meta(df$species) meta(df$species)@format
This is a convenience function, useful to explore the variables of a newly imported dataset.
print_labels(x, name = NULL)print_labels(x, name = NULL)
x |
A labelled vector |
name |
The name of the vector (optional) |
s1 <- labelled(c("M", "M", "F"), c(Male = "M", Female = "F")) s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2)) labelled_df <- tibble::tibble(s1, s2) for (var in names(labelled_df)) { print_labels(labelled_df[[var]], var) }s1 <- labelled(c("M", "M", "F"), c(Male = "M", Female = "F")) s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2)) labelled_df <- tibble::tibble(s1, s2) for (var in names(labelled_df)) { print_labels(labelled_df[[var]], var) }
Currently haven can read and write logical, integer, numeric, character
and factors. See labelled() for how labelled variables in
Stata are handled in R.
Character vectors will be stored as strL if any components are
strl_threshold bytes or longer (and version >= 13); otherwise they will
be stored as the appropriate str#.
read_dta( file, encoding = NULL, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) read_stata( file, encoding = NULL, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_dta( data, path, version = NULL, label = attr(data, "label"), strl_threshold = 2045, adjust_tz = TRUE )read_dta( file, encoding = NULL, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) read_stata( file, encoding = NULL, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_dta( data, path, version = NULL, label = attr(data, "label"), strl_threshold = 2045, adjust_tz = TRUE )
file |
Either a path to a file, a URL, a connection, or a raw vector. Remote files are downloaded before reading. |
encoding |
The character encoding used for the file. Generally, only needed for Stata 13 files and earlier. See Encoding section for details. |
col_select |
Columns to include in the results. You can use the same
mini-language as Predicates using |
skip |
Number of lines to skip before reading data. |
n_max |
Maximum number of lines to read. Set to 0 to return just metadata, i.e. data frame containing correctly typed (but empty) columns along with all data frame and variable metadata. |
progress |
Display a progress bar? The default, |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
data |
Data frame to write. File and variable metadata stored with
|
path |
Path to a file where the data will be written. |
version |
File version to use. Supports versions 8-15. Defaults to
the version recorded in the metadata of |
label |
Dataset label to use, or |
strl_threshold |
Any character vectors with a maximum length greater
than |
adjust_tz |
Stata, SPSS and SAS do not have a concept of time zone,
and all date-time variables are treated as UTC.
|
A tibble, data frame variant with nice defaults.
Variable labels are stored in the "label" attribute of each variable. It is not printed on the console, but the RStudio viewer will show it.
Value labels are preserved with the labelled() class. Labelled vectors
are an intermediate representation that preserves the original value
labels, not a regular R factor. Convert labelled categorical variables
with as_factor(), or remove value labels with zap_labels() if you
need plain R vectors for analysis. See vignette("semantics") for more
details.
The data frame and each variable also carry metadata read from the file;
access it with meta(). See meta_var_sas(), meta_var_spss(), and
meta_var_stata() for the format-specific fields.
Prior to Stata 14, files did not declare a text encoding, and the
default encoding differed across platforms. If encoding = NULL,
haven assumes the encoding is windows-1252, the text encoding used by
Stata on Windows. Unfortunately Stata on Mac and Linux use a different
default encoding, "latin1". If you encounter an error such as
"Unable to convert string to the requested encoding", try
encoding = "latin1"
For Stata 14 and later, you should not need to manually specify encoding
value unless the value was incorrectly recorded in the source file.
The version argument controls which Stata file format is used, which
determines compatibility with different versions and flavours of Stata.
The following table shows the supported versions:
| version | File format | Stata version | Compatible flavours |
| 8-9 | 113 | Stata 8-9 | BE, SE, MP |
| 10-11 | 114 | Stata 10-11 | BE, SE, MP |
| 12 | 115 | Stata 12 | BE, SE, MP |
| 13 | 117 | Stata 13 | BE, SE, MP |
| 14 | 118 | Stata 14+ | BE, SE, MP |
| 15 | 119 | Stata 15+ | MP only |
In most cases you should use the default version = 14:
Versions 8-14 create files readable by all flavours of Stata (Stata/BE, Stata/SE, and Stata/MP).
Version 15 creates format 119 files, designed for datasets exceeding 32,767 variables. These files can only be opened by Stata/MP, even if your dataset has fewer variables. Stata/BE and Stata/SE will refuse to open these files with an error like "dataset too large".
Only use version = 15 if you need to write a dataset with more than 32,767
variables and your recipients have access to Stata/MP.
path <- system.file("examples", "iris.dta", package = "haven") read_dta(path) tmp <- tempfile(fileext = ".dta") write_dta(mtcars, tmp) read_dta(tmp) read_stata(tmp)path <- system.file("examples", "iris.dta", package = "haven") read_dta(path) tmp <- tempfile(fileext = ".dta") write_dta(mtcars, tmp) read_dta(tmp) read_stata(tmp)
read_sas() supports both sas7bdat files and the accompanying sas7bcat files
that SAS uses to record value labels. write_sas() creates sas7bdat files;
it does not write value labels.
The sas7bdat format is closed and undocumented, so if you need an open
format, instead consider write_xpt(), the SAS transport format.
read_sas( data_file, catalog_file = NULL, encoding = NULL, catalog_encoding = encoding, col_select = NULL, skip = 0L, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_sas(data, path)read_sas( data_file, catalog_file = NULL, encoding = NULL, catalog_encoding = encoding, col_select = NULL, skip = 0L, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_sas(data, path)
data_file, catalog_file
|
Data and catalog files. Each can be a path, a URL, a connection, or a raw vector. |
encoding, catalog_encoding
|
The character encoding used for the
|
col_select |
Columns to include in the results. You can use the same
mini-language as Predicates using |
skip |
Number of lines to skip before reading data. |
n_max |
Maximum number of lines to read. Set to 0 to return just metadata, i.e. data frame containing correctly typed (but empty) columns along with all data frame and variable metadata. |
progress |
Display a progress bar? The default, |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
data |
Data frame to write. File and variable metadata stored with
|
path |
Path to file where the data will be written. |
A tibble, data frame variant with nice defaults.
Variable labels are stored in the "label" attribute of each variable. It is not printed on the console, but the RStudio viewer will show it.
Value labels are preserved with the labelled() class. Labelled vectors
are an intermediate representation that preserves the original value
labels, not a regular R factor. Convert labelled categorical variables
with as_factor(), or remove value labels with zap_labels() if you
need plain R vectors for analysis. See vignette("semantics") for more
details.
The data frame and each variable also carry metadata read from the file;
access it with meta(). See meta_var_sas(), meta_var_spss(), and
meta_var_stata() for the format-specific fields.
path <- system.file("examples", "iris.sas7bdat", package = "haven") read_sas(path) tmp <- tempfile(fileext = ".sas7bdat") write_sas(mtcars, tmp) read_sas(tmp)path <- system.file("examples", "iris.sas7bdat", package = "haven") read_sas(path) tmp <- tempfile(fileext = ".sas7bdat") write_sas(mtcars, tmp) read_sas(tmp)
read_sav() reads both .sav and .zsav files; write_sav() creates
.zsav files when compress = TRUE. read_por() reads .por files.
read_spss() uses either read_por() or read_sav() based on the
file extension.
read_sav( file, encoding = NULL, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) read_por( file, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_sav( data, path, compress = c("byte", "none", "zsav"), adjust_tz = TRUE, label = attr(data, "label") ) read_spss( file, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" )read_sav( file, encoding = NULL, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) read_por( file, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_sav( data, path, compress = c("byte", "none", "zsav"), adjust_tz = TRUE, label = attr(data, "label") ) read_spss( file, user_na = FALSE, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" )
file |
Either a path to a file, a URL, a connection, or a raw vector. Remote files are downloaded before reading. |
encoding |
The character encoding used for the file. The default,
|
user_na |
If |
col_select |
Columns to include in the results. You can use the same
mini-language as Predicates using |
skip |
Number of lines to skip before reading data. |
n_max |
Maximum number of lines to read. Set to 0 to return just metadata, i.e. data frame containing correctly typed (but empty) columns along with all data frame and variable metadata. |
progress |
Display a progress bar? The default, |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
data |
Data frame to write. File and variable metadata stored with
|
path |
Path to a file where the data will be written. |
compress |
Compression type to use:
|
adjust_tz |
Stata, SPSS and SAS do not have a concept of time zone,
and all date-time variables are treated as UTC.
|
label |
Dataset label to use, or |
Currently haven can read and write logical, integer, numeric, character
and factors. See labelled_spss() for how labelled variables in
SPSS are handled in R.
A tibble, data frame variant with nice defaults.
Variable labels are stored in the "label" attribute of each variable. It is not printed on the console, but the RStudio viewer will show it.
Value labels are preserved with the labelled() class. Labelled vectors
are an intermediate representation that preserves the original value
labels, not a regular R factor. Convert labelled categorical variables
with as_factor(), or remove value labels with zap_labels() if you
need plain R vectors for analysis. See vignette("semantics") for more
details.
The data frame and each variable also carry metadata read from the file;
access it with meta(). See meta_var_sas(), meta_var_spss(), and
meta_var_stata() for the format-specific fields.
path <- system.file("examples", "iris.sav", package = "haven") read_sav(path) tmp <- tempfile(fileext = ".sav") write_sav(mtcars, tmp) read_sav(tmp)path <- system.file("examples", "iris.sav", package = "haven") read_sav(path) tmp <- tempfile(fileext = ".sav") write_sav(mtcars, tmp) read_sav(tmp)
The SAS transport format is an open format, as is required for submission of data to the FDA.
read_xpt( file, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_xpt( data, path, version = NULL, name = NULL, label = attr(data, "label"), adjust_tz = TRUE )read_xpt( file, col_select = NULL, skip = 0, n_max = Inf, progress = NULL, .name_repair = "unique" ) write_xpt( data, path, version = NULL, name = NULL, label = attr(data, "label"), adjust_tz = TRUE )
file |
Either a path to a file, a URL, a connection, or a raw vector. Remote files are downloaded before reading. |
col_select |
Columns to include in the results. You can use the same
mini-language as Predicates using |
skip |
Number of lines to skip before reading data. |
n_max |
Maximum number of lines to read. Set to 0 to return just metadata, i.e. data frame containing correctly typed (but empty) columns along with all data frame and variable metadata. |
progress |
Display a progress bar? The default, |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
data |
Data frame to write. File and variable metadata stored with
|
path |
Path to a file where the data will be written. |
version |
Version of transport file specification to use: either 5 or 8.
Defaults to the version recorded in the metadata of |
name |
Member name to record in file. Defaults to the table name
recorded in the metadata of |
label |
Dataset label to use, or Note that although SAS itself supports dataset labels up to 256 characters long, dataset labels in SAS transport files must be <= 40 characters. |
adjust_tz |
Stata, SPSS and SAS do not have a concept of time zone,
and all date-time variables are treated as UTC.
|
Value labels are not supported by the transport format, and are silently
ignored by write_xpt().
Note that character limits are expressed in bytes. The number of bytes will often be the same as the number of characters, but strings with multibyte character sequences will count some symbols as more than one character. For example, the string "café" is 5 bytes long in UTF-8.
A tibble, data frame variant with nice defaults.
Variable labels are stored in the "label" attribute of each variable. It is not printed on the console, but the RStudio viewer will show it.
If a dataset label is defined, it will be stored in the "label" attribute of the tibble.
The data frame and each variable also carry metadata read from the file;
access it with meta() and see meta_var_sas() for the available
fields.
write_xpt() returns the input data invisibly.
tmp <- tempfile(fileext = ".xpt") write_xpt(mtcars, tmp) read_xpt(tmp)tmp <- tempfile(fileext = ".xpt") write_xpt(mtcars, tmp) read_xpt(tmp)
"Tagged" missing values work exactly like regular R missing values except that they store one additional byte of information a tag, which is usually a letter ("a" to "z"). Tagged missing values are always lower case characters in R - upper case characters are silently converted to lower case.
tagged_na(...) na_tag(x) is_tagged_na(x, tag = NULL) format_tagged_na(x, digits = getOption("digits")) print_tagged_na(x, digits = getOption("digits"))tagged_na(...) na_tag(x) is_tagged_na(x, tag = NULL) format_tagged_na(x, digits = getOption("digits")) print_tagged_na(x, digits = getOption("digits"))
... |
Vectors containing single character. The letter will be used to "tag" the missing value. Tags are silently converted to lower case. |
x |
A numeric vector |
tag |
If not |
digits |
Number of digits to use in string representation |
format_tagged_na() and print_tagged_na() format tagged
NA's as NA(a), NA(b), etc.
x <- c(1:5, tagged_na("a"), tagged_na("z"), NA) # Tagged NA's work identically to regular NAs x is.na(x) # To see that they're special, you need to use na_tag(), # is_tagged_na(), or print_tagged_na(): is_tagged_na(x) na_tag(x) print_tagged_na(x) # You can test for specific tagged NAs with the second argument is_tagged_na(x, "a") # Because the support for tagged's NAs is somewhat tagged on to R, # the left-most NA will tend to be preserved in arithmetic operations. na_tag(tagged_na("a") + tagged_na("z"))x <- c(1:5, tagged_na("a"), tagged_na("z"), NA) # Tagged NA's work identically to regular NAs x is.na(x) # To see that they're special, you need to use na_tag(), # is_tagged_na(), or print_tagged_na(): is_tagged_na(x) na_tag(x) print_tagged_na(x) # You can test for specific tagged NAs with the second argument is_tagged_na(x, "a") # Because the support for tagged's NAs is somewhat tagged on to R, # the left-most NA will tend to be preserved in arithmetic operations. na_tag(tagged_na("a") + tagged_na("z"))
Convert empty strings into missing values
zap_empty(x)zap_empty(x)
x |
A character vector |
A character vector with empty strings replaced by missing values.
Other zappers:
zap_formats(),
zap_label(),
zap_labels(),
zap_meta(),
zap_widths()
x <- c("a", "", "c") zap_empty(x)x <- c("a", "", "c") zap_empty(x)
This function is deprecated because haven now stores formats in the
haven_meta attribute (see meta()). Please use zap_meta() instead.
zap_formats() only removes the legacy format.stata, format.spss, and
format.sas attributes.
zap_formats(x)zap_formats(x)
x |
A vector or data frame. |
Other zappers:
zap_empty(),
zap_label(),
zap_labels(),
zap_meta(),
zap_widths()
x <- structure(1:3, format.sas = "BEST12.") # Old: zap_formats(x) # New: zap_meta(x)x <- structure(1:3, format.sas = "BEST12.") # Old: zap_formats(x) # New: zap_meta(x)
Removes variable label, leaving unlabelled vectors as is.
zap_label(x)zap_label(x)
x |
A vector or data frame |
zap_labels() to remove value labels.
Other zappers:
zap_empty(),
zap_formats(),
zap_labels(),
zap_meta(),
zap_widths()
x1 <- labelled(1:5, c(good = 1, bad = 5), label = "rating") x1 zap_label(x1) x2 <- labelled_spss(c(1:4, 9), label = "score", na_values = 9) x2 zap_label(x2) # zap_label also works with data frames df <- tibble::tibble(x1, x2) str(df) str(zap_label(df))x1 <- labelled(1:5, c(good = 1, bad = 5), label = "rating") x1 zap_label(x1) x2 <- labelled_spss(c(1:4, 9), label = "score", na_values = 9) x2 zap_label(x2) # zap_label also works with data frames df <- tibble::tibble(x1, x2) str(df) str(zap_label(df))
Removes value labels, leaving unlabelled vectors as is. Use this if you
want to simply drop all labels from a data frame.
Zapping labels from labelled_spss() also removes user-defined missing
values by default, replacing with standard NAs. Use the user_na argument
to override this behaviour.
zap_labels(x, ...) ## S3 method for class 'haven_labelled_spss' zap_labels(x, ..., user_na = FALSE)zap_labels(x, ...) ## S3 method for class 'haven_labelled_spss' zap_labels(x, ..., user_na = FALSE)
x |
A vector or data frame |
... |
Other arguments passed down to method. |
user_na |
If |
zap_label() to remove variable labels.
Other zappers:
zap_empty(),
zap_formats(),
zap_label(),
zap_meta(),
zap_widths()
x1 <- labelled(1:5, c(good = 1, bad = 5)) x1 zap_labels(x1) x2 <- labelled_spss(c(1:4, 9), c(good = 1, bad = 5), na_values = 9) x2 zap_labels(x2) # Keep the user defined missing values zap_labels(x2, user_na = TRUE) # zap_labels also works with data frames df <- tibble::tibble(x1, x2) df zap_labels(df)x1 <- labelled(1:5, c(good = 1, bad = 5)) x1 zap_labels(x1) x2 <- labelled_spss(c(1:4, 9), c(good = 1, bad = 5), na_values = 9) x2 zap_labels(x2) # Keep the user defined missing values zap_labels(x2, user_na = TRUE) # zap_labels also works with data frames df <- tibble::tibble(x1, x2) df zap_labels(df)
Removes the metadata that haven uses to round-trip variables and data frames
between R and SAS/SPSS/Stata (see meta()). This removes the haven_meta
attribute as well as the legacy format.sas, format.spss,
format.stata, display_width, and width attributes on columns and
notes, creation_timestamp, and modified_timestamp attributes on data
frames.
Variable labels, value labels, and user-defined missing values are not
affected; use zap_label(), zap_labels(), and zap_missing() to remove
those.
zap_meta(x)zap_meta(x)
x |
A vector or data frame. |
Other zappers:
zap_empty(),
zap_formats(),
zap_label(),
zap_labels(),
zap_widths()
x <- 1:3 meta(x) <- meta_var_sas(format = "BEST12.") meta(x) meta(zap_meta(x)) # zap_meta() also works with data frames, removing metadata from the # data frame and every column df <- tibble::tibble(x) meta(df) <- meta_df_sas(table_name = "DATA") df <- zap_meta(df) meta(df) meta(df$x)x <- 1:3 meta(x) <- meta_var_sas(format = "BEST12.") meta(x) meta(zap_meta(x)) # zap_meta() also works with data frames, removing metadata from the # data frame and every column df <- tibble::tibble(x) meta(df) <- meta_df_sas(table_name = "DATA") df <- zap_meta(df) meta(df) meta(df$x)
This is useful if you want to convert tagged missing values from SAS or
Stata, or user-defined missings from SPSS, to regular R NA.
zap_missing(x)zap_missing(x)
x |
A vector or data frame |
x1 <- labelled( c(1, 5, tagged_na("a", "b")), c(Unknown = tagged_na("a"), Refused = tagged_na("b")) ) x1 zap_missing(x1) x2 <- labelled_spss( c(1, 2, 1, 99), c(missing = 99), na_value = 99 ) x2 zap_missing(x2) # You can also apply to data frames df <- tibble::tibble(x1, x2, y = 4:1) df zap_missing(df)x1 <- labelled( c(1, 5, tagged_na("a", "b")), c(Unknown = tagged_na("a"), Refused = tagged_na("b")) ) x1 zap_missing(x1) x2 <- labelled_spss( c(1, 2, 1, 99), c(missing = 99), na_value = 99 ) x2 zap_missing(x2) # You can also apply to data frames df <- tibble::tibble(x1, x2, y = 4:1) df zap_missing(df)
This function is deprecated because haven now stores display widths in the
haven_meta attribute (see meta()). Please use zap_meta() instead.
zap_widths() only removes the legacy display_width attribute.
zap_widths(x)zap_widths(x)
x |
A vector or data frame. |
Other zappers:
zap_empty(),
zap_formats(),
zap_label(),
zap_labels(),
zap_meta()
x <- structure(1:3, display_width = 10) # Old: zap_widths(x) # New: zap_meta(x)x <- structure(1:3, display_width = 10) # Old: zap_widths(x) # New: zap_meta(x)