How to read and write SPSS .sav files in R or import data from and export data to SPSS .sav files in R, using read_sav() (haven), and write_sav() (haven).

Below are the functions and the package you need to install.

Packages and Functions for Reading and Writing SPSS .sav Files in R
Activity Package Function
Read SPSS .sav haven read_sav()
Write SPSS .sav haven write_sav()

1 Read or Import Data from SPSS SAV Files in R

Download testdata.sav file.

The SPSS or .sav file format is the standard data storage file format created by the Statistical Package for the Social Sciences (SPSS).

To read or import SPSS or .sav files in R, first install the "haven" package:

install.packages("haven")

Then load the package with the following:

library("haven")

After the installation and loading of the package, if you set or have the working directory as the folder containing the file, you can read or import the SPSS or .sav file with the following line of code:

read_sav("testdata.sav")

Or specify the full path of where the file is located:

read_sav("C:/Users/Public/Statscodes/Rdata/read-files/testdata.sav")
SPSS File Read in R

SPSS File Read in R

To remove the initial messages, you can turn the SPSS input to a dataframe:

data.frame(read_sav("testdata.sav"))
Image 2 of SPSS File Read in R

Image 2 of SPSS File Read in R

2 Write or Export Data to SPSS SAV Files in R

dtfrm = data.frame(Group = c("A", "B", "B", "C", "D"), 
                   ID = c("A02", "B12", "B15", "C04", "D07"), 
                   Score = c(9, 8, 8, 10, 7), 
                   Position = c(2, 3, 3, 1, 5))
dtfrm
  Group  ID Score Position
1     A A02     9        2
2     B B12     8        3
3     B B15     8        3
4     C C04    10        1
5     D D07     7        5

To write or export data to SPSS or .sav files in R, first install the "haven" package:

install.packages("haven")

Then load the package with the following:

library("haven")

After the installation and loading of the "haven" package, you can save the SPSS or .sav file to the working directory with the following line of code:

write_sav(dtfrm, "outdata.sav")

Or specify the full path of where you want to save the file:

write_sav(dtfrm, "C:/Users/Public/Statscodes/Rdata/write-files/outdata.sav")

The SPSS .sav file should look like this in SPSS:

SPSS File Written in R and Loaded in SPSS

SPSS File Written in R and Loaded in SPSS

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes