I'm using haven
to import a .sav
file into R
. I wonder how to show value labels rather than numeric codes. In the following example I want to show Species names rather than numbers 1, 2, 3.
library(haven)
path <- system.file("examples", "iris.sav", package = "haven")
df1 <- read_sav(path)
head(df1)
# A tibble: 6 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <dbl+lbl>
1 5.10 3.50 1.40 0.200 1
2 4.90 3.00 1.40 0.200 1
3 4.70 3.20 1.30 0.200 1
4 4.60 3.10 1.50 0.200 1
5 5.00 3.60 1.40 0.200 1
6 5.40 3.90 1.70 0.400 1
str(df1)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: atomic 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
..- attr(*, "format.spss")= chr "F8.2"
$ Sepal.Width : atomic 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
..- attr(*, "format.spss")= chr "F8.2"
$ Petal.Length: atomic 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
..- attr(*, "format.spss")= chr "F8.2"
$ Petal.Width : atomic 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
..- attr(*, "format.spss")= chr "F8.2"
$ Species :Class 'labelled' atomic [1:150] 1 1 1 1 1 1 1 1 1 1 ...
.. ..- attr(*, "format.spss")= chr "F8.0"
.. ..- attr(*, "labels")= Named num [1:3] 1 2 3
.. .. ..- attr(*, "names")= chr [1:3] "setosa" "versicolor" "virginica"
Found a very simple solution within
haven
packageYou may use a function called
characterize()
orfactorize()
from rio package to do the conversion of this type of data structure.for example:
If you choose characterize, the column is converted to character, but in case you choose to use factorize, the column is converted to factor.
You may visit here for reference:
Not sure you wanted like this or not, May be you want to convert it while importing.
Thanks, I hope this helps.
Running the conversion using
factorize()
.Output: