Use of haven to read .sav (SPSS_ files): Change labelled vector to character string or factor

2.2k views Asked by At

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?

2

There are 2 answers

0
aosmith On BEST ANSWER

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:

df$instructional_practice = as_factor(df$instructional_practice)

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.

df = as_factor(df)
1
IRTFM On

At the moment it is very much like an R factor and I'm guessing (although it's kind of vague) you either want an R factor or you want a character vector. If you wanted an R character vector with values substituted for the current numeric values you could use the numeric values as an index into the names of the labels attribute:

 newvec <- names( attr( f$instructional_practice , "labels"))[f$instructional_practice]