How to change class of variable 'labelled' into string or chr in R?

Viewed 2172

How can i change a variable of class 'labelled' into a character variable only showing the labels as string or character? So i only want to see the last attribute, see below for the structure of my variable.

Class 'labelled'  atomic [1:918] 4 12 13 20 26 36 40 1 4 13 ...
..- attr(*, "format.spss")= chr "F8.0"
..- attr(*, "labels")= Named num [1:40] 1 2 3 4 5 6 7 8 9 10 ...
.. ..- attr(*, "names")= chr [1:40] "People management" "HR" "Self management" "Email" ...
2 Answers

@shiro has an excellent solution for this. Expounding a bit. Here's a general solution for other problems like it:

library(haven)
s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2)) # example from haven:labelled
# use the default str method to see what s2 is 'inside'
utils:::str.default(s2)

# 'haven_labelled' num [1:3] 1 1 2
# - attr(*, "labels")= Named num [1:2] 1 2
# ..- attr(*, "names")= chr [1:2] "Male" "Female"

# It's a numeric vector with an attribute, labels
# labels is itself a numeric vector with the attribute names
# names is a character vector

# So take the attribute's attribute and subset with the numerics

attr(attr(s2,'labels'),'names')[s2]
Related