David Jorquera
David Jorquera

Reputation: 2102

Extract haven_labelled vector's label as a vector of strings

I've got a haven_labelled vector, from which I want to extract its labels as a vector of strings:

library(haven)
vec <- structure(c(1, 2, 3, 1, 2, 3), label = "Región", labels = c(`one` = 1, `two` = 2, `three` = 3), 
                 class = "haven_labelled")

vec

#   <Labelled double>: Región
#[1] 1 2 3 1 2 3

#Labels:
# value label
#     1   one
#     2   two
#     3 three

attr(vec, "labels") doesn't do what I want since it returns a named vector:

#  one   two three 
#    1     2     3 

Desired output:

c("one", "two", "three")

I've visited a lot of documentation and can't get to a solution, so your help would be very much welcome!

Upvotes: 3

Views: 1116

Answers (1)

akrun
akrun

Reputation: 887168

It is a named vector, so use names to extract the names of that vector

names(attr(vec, "labels"))
#[1] "one"   "two"   "three"

Upvotes: 5

Related Questions