5.4 Working with Data from SPSS, SAS, and Stata Files

Now, you know how to export and import data from delimited files and Excel files. In the section, you will learn how to export and import data from other statistical software including SPSS, SAS, and Stata. We will use the package haven, another member of the tidyverse family.

5.4.1 Export and Import SPSS Files

Let’s first load the package haven, and prepare a data frame for exporting.

library(haven)
dig_num <- 7:1
ani_char <- c("sheep", "pig", "monkey", "pig", "monkey", NA, "pig")
conditions <- c("Excellent", "Good", "N", "Fair", "Good", "Good", "Excellent")
my_animals<- tibble(dig_num, ani_char,conditions)
my_animals

The data frame my_animals will be used as in Section 5.1. You can use the function write_sav() to export a data frame into a SPSS .sav file.

write_sav(my_animals, "my_animals.sav")

To read a SPSS file ending in .sav or .por, you can use the function read_spss() which will automatically call read_sav() for .sav files and read_por() for .por files.

my_animals_spss <- read_spss("my_animals.sav")
head(my_animals_spss)
#> # A tibble: 6 × 3
#>   dig_num ani_char conditions
#>     <dbl> <chr>    <chr>     
#> 1       7 "sheep"  Excellent 
#> 2       6 "pig"    Good      
#> 3       5 "monkey" N         
#> 4       4 "pig"    Fair      
#> 5       3 "monkey" Good      
#> 6       2 ""       Good

5.4.2 Export and Import SAS Files

You can use the function write_sas() to export a data frame into a SAS .sas7bdat file.

write_sas(my_animals, "my_animals.sas7bdat")

To import a SAS file, you can use the function read_sas().

my_animals_sas <- read_sas("my_animals.sas7bdat")
head(my_animals_sas)
#> # A tibble: 6 × 3
#>   dig_num ani_char conditions
#>     <dbl> <chr>    <chr>     
#> 1       7 "sheep"  Excellent 
#> 2       6 "pig"    Good      
#> 3       5 "monkey" N         
#> 4       4 "pig"    Fair      
#> 5       3 "monkey" Good      
#> 6       2 ""       Good

5.4.3 Export and Import Stata Files

Lastly, let’s talk about Stata files. You can use the function write_dta() to export a data frame into a Stata .dta file.

write_dta(my_animals, "my_animals.dta")

To read a Stata file ending in .dta, you can use the function read_dta().

my_animals_stata <- read_dta("my_animals.dta")
head(my_animals_stata)
#> # A tibble: 6 × 3
#>   dig_num ani_char conditions
#>     <dbl> <chr>    <chr>     
#> 1       7 "sheep"  Excellent 
#> 2       6 "pig"    Good      
#> 3       5 "monkey" N         
#> 4       4 "pig"    Fair      
#> 5       3 "monkey" Good      
#> 6       2 ""       Good

5.4.4 Import using the menu

Similarly as Sections 5.2 and 5.3, you can also use the menu in Table 5.1 to import SPSS, SAS, and Stata Files.

5.4.5 Exercise