haven R Package

repository·main·Indexed 19 days ago

https://github.com/tidyverse/haven

A tidyverse package that enables R to read and write data formats used by SAS, SPSS, and Stata by wrapping the ReadStat C library. It provides functions such as read_sas(), read_sav(), and read_dta() to import data as tibbles while preserving value labels via the labelled() class.

Tokens
554
Snippets
2
Records
4
Agent score
16%

What's inside haven

  1. Overview of haven supported formats

    main

    Haven provides R interfaces to read and write data formats used by SAS, SPSS, and Stata by wrapping the ReadStat C library.

    Supported Formats

    • SAS:
      • read_sas(): Reads .sas7bdat and .sas7bcat files.
      • read_xpt(): Reads SAS transport files (versions 5 and 8).
      • write_xpt(): Writes SAS transport files (versions 5 and 8).
    • SPSS:
      • read_sav(): Reads .sav files.
      • read_por(): Reads older .por files.
      • write_sav(): Writes .sav files.
    • Stata:
      • read_dta(): Reads .dta files (up to version 15).
      • write_dta(): Writes .dta files (versions 8-15).
  2. How haven handles data types and semantics

    main

    When reading data with haven, the output follows these conventions:

    • Tibbles: Data is returned as tibbles, which provide improved printing for long or wide datasets.
    • Value Labels: Original semantics are preserved using a labelled() class. These can be converted to R factors using as_factor(). Special missing values are also preserved.
    • Dates and Times: Automatically converted to standard R date/time classes.
    • Characters: Character vectors are kept as characters and are not automatically converted to factors.
  3. Read and write SAS, SPSS, and Stata files

    main

    Use the following functions to import and export data from common statistical software formats. Ensure you have loaded the library with library(haven) first.

    library(haven)
    
    # SAS
    read_sas("mtcars.sas7bdat")
    write_xpt(mtcars, "mtcars.xpt")
    
    # SPSS
    read_sav("mtcars.sav")
    write_sav(mtcars, "mtcars.sav")
    
    # Stata
    read_dta("mtcars.dta")
    write_dta(mtcars, "mtcars.dta")
  4. Install haven

    main

    You can install haven either as part of the full tidyverse suite or as a standalone package using install.packages().

    # The easiest way to get haven is to install the whole tidyverse:
    install.packages("tidyverse")
    
    # Alternatively, install just haven:
    install.packages("haven")