Learn R Programming

DDIwR (version 0.24)

convert: Converts a dataset from one statistical software to another

Description

This function converts (or transfers) between R, Stata, SPSS, SAS, Excel and DDI XML files. It uses the DDI standard as an exchange platform and facilitates a consistent conversion of missing values. Statistical files are read and written through ReadStat directly, without the haven package.

Usage

convert(
  from,
  to = NULL,
  declared = TRUE,
  chartonum = FALSE,
  recode = TRUE,
  encoding = "UTF-8",
  csv = NULL,
  n_max = -1L,
  skip = 0L,
  ...,
  catalog = NULL,
  setup = TRUE
)

Value

An invisible R data frame, when the argument to is NULL.

Arguments

from

A path to a file, or a data.frame object

to

Character, the name of a software package or a path to a specific file

declared

Logical, return the resulting dataset as a declared object

chartonum

Logical, recode character categorical variables to numerical categorical variables

recode

Logical, recode missing values

encoding

The character encoding used to read a file

csv

Complex argument, see the Details section

n_max

Integer, maximum number of rows to import from SPSS, Stata or SAS files

skip

Integer, number of rows to skip when importing from SPSS, Stata or SAS files

...

Additional options specific to the source or destination format, including language when importing translated DDI labels and catalog_encoding when reading a SAS catalog. See the Details section.

catalog

Path to a SAS format catalog. For .sas7bdat output this is the destination catalog. For other conversions from .sas7bdat it is the input catalog. Omit to use the matching filename convention or pass NULL to skip the catalog for that operation.

setup

Logical, write the companion SAS setup script for labelled XPT output. Defaults to TRUE.

Author

Adrian Dusa

Details

When the argument to specifies a certain statistical package ("R", "Stata", "SPSS", "SAS", "XPT") or "Excel", the name of the destination file will be identical to the one in the argument from, with an automatically added software specific extension. to = "SAS" retains the XPT destination. Supply an explicit .sas7bdat path to select native SAS7BDAT output.

SPSS portable file (with the extension ".por") can only be read, but not written.

SPSS exports default to byte compression for .sav destinations and ZSAV compression for .zsav destinations. Supply compress = "none", "byte" or "zsav" through ... to override that default. compress = FALSE selects no compression and compress = TRUE selects ZSAV compression.

SAS transport exports (.xpt or to = "SAS") accept data frames without labels. A companion SAS setup script is generated only when the data has variable or value labels. Value labels alone are enough. The script uses the XPT output's base name and directory and targets the SAS dataset with that name in that directory.

SPSS system files (.sav and .zsav) preserve custom dataset and variable attributes. They are stored in the R attribute spss.attributes on the data frame and on each column, as a named list of character vectors. For example, attr(data, "spss.attributes") <- list(source = "Archive") and attr(data$answer, "spss.attributes") <- list(foo = "bar") are written as SPSS dataset and variable attributes, respectively. A character vector with several elements represents an attribute array; a single element represents a scalar. Custom names such as label remain separate from standard R metadata. Names must be valid SPSS attribute names of at most 64 UTF-8 bytes, unique ignoring case within their scope. Values must be non-missing strings without line feeds, which the SPSS attribute format cannot represent.

Stata dataset and variable characteristics are preserved in .dta files through the R attribute stata.characteristics on the data frame and each column. Use a named list of single, non-missing strings, for example attr(data, "stata.characteristics") <- list(Source = "Archive") and attr(data$answer, "stata.characteristics") <- list(Foo = "bar"). Characteristic names are case sensitive and may contain at most 32 characters. Values may contain line feeds and trailing spaces, and may use at most 67783 bytes in the target encoding (67784 including the terminating zero byte). Stata 14 and later use UTF-8. Earlier versions write characteristic values in Windows-1252 and require ASCII characteristic names; unrepresentable values are rejected. When importing these older files with convert(), specify encoding = "windows-1252" (or their actual source encoding). Dataset and variable note characteristics, including note0, are retained. Raw dataset note characteristics take precedence over the legacy R notes attribute when writing, preserving note numbering and contents. If no raw note characteristics are present, dataset notes are written as Stata note characteristics.

Import to R and conversion to RDS retain the formats, storage widths, display widths, temporal classes and units, and custom SPSS/Stata metadata returned by the readers, including during declared conversion and missing recoding. Dataset labels and notes are retained in R. Character-to-numeric recoding removes obsolete string formats and storage widths. Preservation in exported statistical files depends on the destination writer's support.

SPSS exports and the native SAS7BDAT writer preserve the data frame's label attribute as the dataset label. When exporting to SPSS, label in ... overrides that attribute: convert(data, "data.sav", label = "Survey"). An explicit label = NULL or label = "" clears the exported dataset label; omitting the argument retains it. Variable labels and custom attributes named label are separate. Dataset labels must be single, non-missing character strings of at most 64 UTF-8 bytes for SPSS or 256 bytes for native SAS7BDAT, or NULL. Invalid labels cause an error before opening the destination file. Trailing padding spaces are removed on import. Export does not modify the input object's label.

Optional spss_metadata, stata_metadata and sas_metadata attributes group format-specific metadata in ordinary named R lists on data frames or columns. These are DDIwR's metadata containers. Field names must be nonempty and unique. Statistical file readers store formats, storage widths, display widths and dataset notes only in these lists. Shared attributes such as label, labels, na_values and na_range remain separate. Edit the list fields after import; legacy attributes are accepted as writer fallbacks for older R objects but are not emitted by readers.

Writers use explicit arguments first, then fields in the destination vendor's list, then existing attributes, then their usual defaults. A missing list field falls back to the existing attribute; a present NULL field clears it and uses the writer default. For example, attr(data$answer, "spss_metadata") <- list(format = "F12.3") overrides format.spss, while list(format = NULL) clears it. Other vendors' lists are not interpreted. Input objects are not modified. Use vendorMetadata() to read or replace list fields without editing attributes. Use clearFormats() or clearWidths() to remove the corresponding column metadata from both vendor lists and existing attributes, preventing legacy fallback from restoring cleared fields.

Supported column fields are format for all three vendors, width for all three vendors, and display_width, measure and alignment for SPSS. SPSS measurement levels are "nominal", "ordinal" and "scale"; alignments are "left", "right" and "center". SAS also supports informat. Formats and informats are single, non-missing, nonempty strings; widths are nonnegative whole numbers up to R's integer maximum. String storage is enlarged when needed to fit the values. Numeric storage width is fixed at eight bytes in SAV output. Numeric SAS7BDAT and XPT widths must be 3 through 8 bytes, or 0 for the eight-byte default. Native SAS7BDAT output discards the least significant bytes of the stored double, which can change fractions and large integers. Date/time values are shortened after conversion to SAS units. Use eight bytes to retain full precision. Numeric SAS7BDAT widths in the existing width attribute follow the same rules. Invalid widths cause an error before opening the destination.

Stata column type selects "byte", "int", "long", "float", "double" or "strL". Numeric storage must represent all exported values exactly, including converted date/time units; unsafe choices cause an error. Clear type to restore automatic storage selection after editing values. "strL" requires a character column and Stata 13 or later. Readers retain numeric storage types and strL in stata_metadata. Fixed Stata string width records the on-disk byte capacity, excluding the buffer terminator.

Dataset notes are supported for SPSS and Stata as character vectors without missing values. SPSS notes allow at most 80 UTF-8 bytes per entry, including empty entries; trailing padding spaces are removed on import. Stata list notes override both legacy notes and raw dataset note characteristics. Unchanged imported notes retain their original raw numbering; other characteristics remain intact. Dataset version uses Stata release numbers 8 through 15, or 5 and 8 for SAS XPT. On import, shared Stata file formats map to the earliest supported release that writes them (8, 10, 12, 13, 14 or 15). Without metadata, convert() defaults to Stata 14 or XPT 5; version = NULL explicitly selects that default. SAS dataset table_name is supported for SAS7BDAT and XPT, and supplies the default for the XPT writer's name argument.

Dataset created and modified timestamps are read as POSIXct values displayed in UTC. Fields are included only when the format provides a timestamp that the reader can parse. Blank or unavailable timestamps remain absent through conversion, recoding and RDS storage; the Unix epoch (zero) is a valid timestamp and is not treated as missing. SPSS and Stata imports expose their single header timestamp as created, without a modified field. created can be written for all three vendors, and sas_metadata$modified can be written to SAS7BDAT and XPT versions 5 and 8. Each writable timestamp must be one finite POSIXct value with whole-second precision. An absent or NULL modified uses the creation timestamp; setting only modified leaves creation at the writer's current-time default. The current-time default also applies when exporting without created. Local time is used for file headers without timezone information; Stata timestamps have minute precision. SPSS creation years must be 1970 through 2069 and both XPT timestamps must use years 1960 through 2059 because their headers use two-digit years. XPT imports use the dataset member's timestamps, falling back to the corresponding library timestamps when the member fields are blank. Creation and modification are resolved independently; one does not substitute for the other. SAS7BDAT stores separate UTC offsets for the two timestamps, preserving instants across timezone changes. SPSS and Stata headers have no separate modification timestamp: spss_metadata$modified and stata_metadata$modified remain preserved in R and RDS but are ignored on export, leaving the creation timestamp unchanged.

SPSS multiple-response definitions are read and written through dataset spss_metadata$mr_sets, a list named by set name. Each entry contains type, label, is_dichotomy, counted_value, counted_string, variables and label_from_var_label. Counted fields apply to dichotomies; counted_string retains the source token, including string values. Variable references use long variable names; exports translate them to the file's short names. Definitions are retained in R and RDS and written in SAV and ZSAV files.

To create a set, supply type ("C" for categories, "D" for dichotomies labelled by variables, or "E" for dichotomies labelled by counted values) and at least two distinct, existing variables, all numeric or all string. Set names must begin with $, follow SPSS naming rules, fit in 64 UTF-8 bytes, and be unique ignoring case. For example, this defines a numeric dichotomy set:

attr(data, "spss_metadata") <- list(mr_sets = list(
    "$choices" = list(type = "D", variables = c("first", "second"), counted_value = 1)
))

Optional label defaults to "" and is limited to 256 UTF-8 bytes. label_from_var_label = TRUE is allowed only for type "E" with an empty label. is_dichotomy, when supplied, must agree with type.

For dichotomies, counted_string takes precedence over counted_value. Numeric sets require an integer token or a finite whole-number counted_value; string sets require counted_string, which must fit the narrowest exported member. Category sets cannot specify either counted field. Trailing padding spaces are removed from counted strings; imported labels also lose trailing padding spaces. Labels and counted strings cannot contain line breaks. Unknown fields, invalid definitions and missing member variables cause an error before opening the destination. NULL or empty mr_sets writes no definitions. Files group types "C" and "D" before "E", preserving relative set order within each group.

All list fields, including unsupported ones, are retained during conversion to R or RDS and missing-value recoding. Character-to-numeric recoding removes list fields describing string storage (format, width, SAS informat and Stata type). Export warns about non-NULL destination-vendor fields the writer cannot honor, apart from the read-only dataset modified field for SPSS and Stata. These lists are separate from custom spss.attributes and stata.characteristics. Malformed lists and supported fields with invalid types or shapes cause an error before the destination file is opened. The native writers also enforce their format-specific restrictions.

Stata export converts R Date columns to days since 1960-01-01 and POSIXct columns to milliseconds since that date. Integer storage is used only when the converted values fit its range and precision. System and extended missing values are preserved separately from the date/time values.

The argument to can also be specified as a path to a specific file, in which case the software package is determined from its file extension. Home-directory paths beginning with ~ are supported. DDI exports include the required study description with generic defaults. Supply titl, IDNo, agency, distrbtr, URI and abstract through ... to describe the actual study. XML exports are validated against the bundled DDI Codebook 2.6 schema before writing. Invalid XML causes an error and leaves destination files unchanged. The following extentions are currently recognized: .xml for DDI, .rds for R, .dta for Stata, .sav and .zsav for SPSS, .xpt for SAS, and .xlsx for Excel.

Additional parameters can be specified via the three dots argument ..., for the destination or source format. For example, version selects the Stata release when writing a .dta file. Excel import options are passed to readxl.

The formal arguments n_max and skip are used only when importing foreign data files through the direct ReadStat readers, namely SPSS (.sav, .zsav, .por), Stata (.dta) and SAS (.sas7bdat, .xpt). They can be used to read only the first n_max rows or to import large files in batches by skipping the first skip rows. Use inspectFile() to inspect column definitions and metadata without decoding observations, including the original row count when the file's metadata provides one. Unlike inspection, n_max = 0 uses a limited data read.

SPSS user-defined missing codes are retained by default. Specify user_na = FALSE in convert() to discard them during import.

The same three dots argument is used to pass additional parameters to other functions in this package, for instance exportCodebook() when writing to a DDI file. One of its argument embed (activated by default) can be used to control embedding the data in the XML file. Deactivating it will create a CSV file in the same directory, using the same file name as the XML file.

When converting from DDI, if the dataset is not embedded in the XML file, the CSV file is expected to be found in the same directory as the DDI Codebook, and it should have the same file name as the XML file. The path to the CSV file can be provided via the csv argument. Additional formal parameters of the function read.csv() can be passed via the same three dots ... argument. Alternatively, the csv argument can also be an R data frame.

A multilingual DDI Codebook is imported in one language at a time. The DDI-specific language option is supplied via ..., for example convert("codebook.xml", language = "en"). When it is omitted, the effective xml:lang of the first variable label is used. Supplying it selects that translation throughout the variable and category labels. Language declarations inherited from a parent DDI element are honored. An unqualified label is used as a neutral fallback, but a label in a different language is not substituted.

When converting to DDI, if the argument embed is set to FALSE, users have the option to save the data in a separate CSV file (the default) or not to save the data at all, by setting csv to FALSE.

The DDI .xml file generates unique IDs for all variables, if not already present in the attributes. These IDs are useful for referencing purposes, in newer versions of the DDI Codebook.

The argument chartonum signals recoding character categorical variables, and employs the function recodeCharcat(). This only makes sense when recoding to Stata, which does not allow allocating labels for anything but integer variables.

If the argument to is left to NULL, the data is (invisibly) returned to the R enviroment. Conversion to R, either in the working space or as a data file, will result (by default) in a data frame containing declared labelled variables, as defined in package declared.

The current version reads DDI Codebook versions 1.2.2, 2.5 and 2.6, and creates version 2.6, with future versions to extend the functionality for DDI Lifecycle versions 3.x and link to the future package DDI4R for the UML model based version 4. It extends the standard DDI Codebook by offering the possibility to embed a serialized version of the R dataset into the XML file containing the Codebook, within a notes child of the fileDscr component. This type of generated codebook is unique to this package and automatically detected when converting to another statistical software. This will likely be replaced with a time insensitive text version.

Native SAS import uses ReadStat directly. When reading a .sas7bdat file into R or another format, catalog gives the path to its input format catalog. Omit catalog to look for a companion .sas7bcat file with the same base name in the same directory, or set catalog = NULL to read only the dataset. When a catalog does not declare an encoding, it inherits the effective data-file encoding. Use encoding and catalog_encoding to override their encodings independently; a catalog override does not affect data-file decoding.

Catalog labels for .A through .Z use numeric keys -91 through -116 in the R labels attribute. A label for ._ retains an underscore-tagged NA key, distinct from the ordinary NA key for system missing. These keys also apply to dates and timestamps and are preserved in RDS storage.

Standalone SAS7BDAT and XPT output does not contain value-label definitions. When writing a .sas7bdat file, catalog gives the output catalog path. Omit it to write a companion .sas7bcat file with the same base name in the same directory whenever the exported columns have value labels (including factor levels) or SAS catalog rules. Set catalog = NULL to write only the dataset.

Export replaces any existing file at the output catalog path, including when the path is chosen automatically.

When both paths are .sas7bdat files, catalog controls the output and the input catalog is discovered by its matching name. To use an input catalog with a different name or location, read the dataset into R first.

data <- convert("input.sas7bdat", catalog = "input-labels.sas7bcat", recode = FALSE)
convert(data, "output.sas7bdat", catalog = "output-labels.sas7bcat")

Native SAS7BDAT output preserves system missing, ._ and existing letter missing tags using SAS's native ordinal encoding at every numeric storage width. Readers also accept the older ASCII-tagged representation. Automatically generated dictionaries assign other missing codes to unused letters. An explicit dictionary can override that mapping. Native output does not generate an additional SAS setup script. Other destinations retain their existing behavior. Numeric, integer and logical columns, including factor codes, can have exact numeric value labels, system missing labels, ._ and .A through .Z labels. Character columns accept named character vectors of exact value-label keys, including an empty key for the blank character value. Keys must be non-missing and at most 32767 UTF-8 bytes. Trailing ASCII spaces are removed from character keys to match SAS padding semantics; leading spaces and other characters remain significant. Character label text retains its leading and trailing spaces, including empty labels. Keys that become duplicates after removing padding cause an error. NA_character_ is not a catalog key; use "" for a blank key. Unused definitions and empty datasets are supported. Labelled Date, POSIXct, hms and difftime columns are supported. Ordinary label keys use the column's R units, just like its data values: days since 1970 for dates, seconds since 1970 for timestamps, and the column's declared units for durations. Export converts both rows and keys to SAS days/seconds since 1960 or time seconds. Durations are normalized to seconds on import; timestamps retain their instant and are returned in UTC. System and extended missing-label keys are categories, never shifted or scaled. Numeric and character ranges, endpoint exclusions, LOW/HIGH and OTHER rules use column sas_metadata$catalog_rules, a data frame with character fields start, end, label, hlo, sexcl and eexcl, integer default and numeric fuzz. end defaults to start, hlo to "", exclusions to "N", default to the longest label's byte width (at least one), and fuzz to zero. default and fuzz must be constant within each format. HLO accepts "", "L", "H", "LH" or "O"; exclusions accept "N" or "Y". An OTHER row has no endpoints; L/H mark unbounded ordinary numeric/character bounds. Numeric endpoints are strings containing finite SAS numbers or missing tokens ".", "._", ".A" through ".Z". Temporal endpoints use native SAS units (days/seconds since 1960 or time seconds), as in PROC FORMAT/CNTLIN, rather than R date/time units. Character endpoints retain leading spaces and drop trailing ASCII padding. Endpoints and labels allow up to 32767 UTF-8 bytes, subject to native record/page capacity. Overlapping or empty intervals, multiple OTHER rows and unsupported rule fields are rejected before publication. Rule tables take precedence over labels; a NULL table restores exact labels. Imported ranges are retained as rules, never misrepresented as point labels; exact entries remain available in labels. Native default widths and numeric fuzz are retained. Rules are written only with a paired catalog. Multilabel, PICTURE, nested formats and executable expressions are not supported. Catalog output uses the native 64-bit layout, including SAS directory, index and format records. SAS catalogs depend on host layout; compatibility is checked with SAS 9.4M9 on Linux x86-64 in UTF-8.

A custom label format cannot also identify a temporal type. Paired temporal export therefore supplies an absent sas_metadata$informat as DATE9, DATETIME25.6 or TIME20.6. An existing compatible informat is retained; an explicitly NULL, unrecognized or conflicting informat causes an error. On SAS import, a recognized temporal display format takes precedence; otherwise a recognized temporal informat determines the date/time class and unit conversion, even without a catalog. Ordinary catalog keys follow the same conversion; missing-code surrogates remain unchanged.

A labelled column's SAS format reference must name a user-defined format. Numeric names allow up to 32 ASCII letters, digits and underscores, starting and ending with a letter or underscore. Character format names use a $ prefix followed by up to 31 such characters. The prefix must match the column's type; numeric and character names are distinct. Display width is preserved separately. Decimal places apply only to numeric formats. Common built-in display formats are rejected; use clearFormats() before export to request generated names. Missing or explicitly cleared references get unique DDI...F names for numeric columns or $DDI...F for character columns. Columns can share a format only when their exported keys and label texts agree. Label texts must be non-missing and at most 32767 UTF-8 bytes each. Duplicate keys, conflicting definitions and reduced numeric widths that cannot retain a label key exactly cause an error.

Catalog imports retain a sas_metadata$label_tags character vector aligned with the value labels: "" for ordinary keys, "." for system missing, "_" or an uppercase letter for tagged missing. This distinguishes label definitions even when no observations use them, without treating ordinary negative values as missing. Paired exports use these tags and the same missing-code dictionary as the data writer; mismatched tag-vector lengths and stale definitions cause an error. label_tags applies only to numeric label definitions and must be absent or NULL for character catalogs. Standalone SAS7BDAT and XPT exports retain their existing behavior and do not write these label definitions.

Paired export writes both files to temporary siblings before replacing the destinations. Publication retains backups and attempts to restore both originals if publication fails. Another process may observe the files between publication steps. SAS value-label catalogs can also be supplied as setup commands. See setupfile().

The argument recode controls how missing values are treated. If the input file has SPSS like numeric codes, they will be recoded to extended (a-z) missing types when converting to Stata or SAS. If the input has Stata like extended codes, they will be recoded to SPSS like numeric codes.

Missing values are harmonized across the entire dataset by default when exporting to Stata or SAS. This automatically builds a dataset-level missing value dictionary when possible. Use harmonize = FALSE via the three dots argument to deactivate this behavior. The alias harmonise = FALSE is also accepted. If the dataset-level dictionary exceeds 26 codes, conversion falls back to separate dictionaries for each variable. A variable with more than 26 distinct numeric missing codes cannot be represented this way and export fails. SAS's additional ._ tag is preserved as an NA with the name "_" in the column's na_index attribute, for numeric columns, dates and timestamps. It does not consume a letter-tag dictionary entry; the A-Z tags retain their existing numeric codes from -91 to -116.

The character encoding is passed to the direct ReadStat readers that accept an encoding override. Set it to NULL to use the file's encoding information and the reader's fallback.

Converting to SPSS works with numerical and character labelled vectors, with or without labels. The native date/time adapters write SPSS dates and timestamps as seconds since 1582-10-14, SAS dates as days since 1960-01-01, and SAS timestamps as seconds since 1960-01-01. Integer-backed R temporal columns use double storage when exporting to SPSS or SAS to avoid overflow. SPSS user-missing codes and ranges remain separate from date/time values; they are retained when importing with user_na = TRUE and discarded with user_na = FALSE.

References

DDI - Data Documentation Initiative, see the DDI Alliance website.

See Also

setupfile, getCodebook, declared

Examples

Run this code
if (FALSE) {
# Assuming an SPSS file called test.sav is located in the working directory
# The following command imports the file into the R environment:
test <- convert("test.sav")

# The following command will extract the metadata in a DDI Codebook and
# produce a test.xml file in the same directory
convert("test.sav", to = "DDI")

# The data may be saved separately from the DDI file, using:
convert("test.sav", to = "DDI", embed = FALSE)

# Format-specific options are supplied through the three dots. For example,
# import the English labels from a multilingual DDI Codebook using:
test <- convert("test.xml", language = "en")

# To produce a Stata file:
convert("test.sav", to = "Stata")

# To produce an R file:
convert("test.sav", to = "R")

# To produce an Excel file:
convert("test.sav", to = "Excel")
}

Run the code above in your browser using DataLab