How to Import SPSS .sav File into R (Example Code)
In this article you’ll learn how to import an SPSS .sav file in R programming.
Preparing the Example
data(iris) # Load iris data set in R head(iris) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Load iris data set in R head(iris) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("haven") # Install & load haven package library("haven") |
install.packages("haven") # Install & load haven package library("haven")
write_sav(iris, "iris.sav") # Exporting example data with write_sav function # # A tibble: 6 x 5 # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # <dbl> <dbl> <dbl> <dbl> <dbl+lbl> # 1 5.1 3.5 1.4 0.2 1 [setosa] # 2 4.9 3 1.4 0.2 1 [setosa] # 3 4.7 3.2 1.3 0.2 1 [setosa] # 4 4.6 3.1 1.5 0.2 1 [setosa] # 5 5 3.6 1.4 0.2 1 [setosa] # 6 5.4 3.9 1.7 0.4 1 [setosa] |
write_sav(iris, "iris.sav") # Exporting example data with write_sav function # # A tibble: 6 x 5 # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # <dbl> <dbl> <dbl> <dbl> <dbl+lbl> # 1 5.1 3.5 1.4 0.2 1 [setosa] # 2 4.9 3 1.4 0.2 1 [setosa] # 3 4.7 3.2 1.3 0.2 1 [setosa] # 4 4.6 3.1 1.5 0.2 1 [setosa] # 5 5 3.6 1.4 0.2 1 [setosa] # 6 5.4 3.9 1.7 0.4 1 [setosa]
Example: Reading SPSS .sav File to R
iris_import_tibble <- read_sav("iris.sav") # Importing data as tibble head(iris_import_tibble) # Print tibble in RStudio # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 1 # 2 4.9 3.0 1.4 0.2 1 # 3 4.7 3.2 1.3 0.2 1 # 4 4.6 3.1 1.5 0.2 1 # 5 5.0 3.6 1.4 0.2 1 # 6 5.4 3.9 1.7 0.4 1 |
iris_import_tibble <- read_sav("iris.sav") # Importing data as tibble head(iris_import_tibble) # Print tibble in RStudio # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 1 # 2 4.9 3.0 1.4 0.2 1 # 3 4.7 3.2 1.3 0.2 1 # 4 4.6 3.1 1.5 0.2 1 # 5 5.0 3.6 1.4 0.2 1 # 6 5.4 3.9 1.7 0.4 1
iris_import_dataframe <- as.data.frame(iris_import_tibble) # Convert tibble to data.frame head(iris_import_dataframe) # Print data.frame in RStudio |
iris_import_dataframe <- as.data.frame(iris_import_tibble) # Convert tibble to data.frame head(iris_import_dataframe) # Print data.frame in RStudio