I am using the haven
library to read an .sav
(SPSS) file into R.
Some of the values are read as a labelled
vector
.
Here is an example of one:
> str(df$instructional_practice)
Class 'labelled' atomic [1:4136] 2 2 6 6 8 8 NaN NaN 17 1 ...
..- attr(*, "label")= chr "intructional practice teacher is using when signaled"
..- attr(*, "format.spss")= chr "F8.2"
..- attr(*, "labels")= Named num [1:18] 1 2 3 4 5 6 7 8 9 10 ...
.. ..- attr(*, "names")= chr [1:18] "1 Lecture" "2 Seatwk-Ind" "3 Review-Ind" "4 Seatwk-Grp" ...
How can I have the values for the vector
be the label names?
You can use
haven::as_factor
to convert labelled vectors to factors, using the labels as the levels.You can use this on individual vectors:
But you can also use it on the entire data.frame. By default using
as_factor
on a data.frame will convert all labels to the factor levels for any labelled variable.