2

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!

David Jorquera
  • 2,046
  • 12
  • 35

1 Answers1

4

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

names(attr(vec, "labels"))
#[1] "one"   "two"   "three"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @akrun unrelated to the Q, but did you ever solve sub-setting list of dataframes with a vector of names ? where, the names appear as column names for some df and as rows in another dfs'. But, both these are part of the list of df;s ? If so, Can you point me to your sol or I can write one more Q – user5249203 Feb 07 '20 at 22:14
  • @user5249203 Ddid you meant `lapply(lst1, function(dat) dat[intersect(names(dat), vec1)])` The rows part is not clear. If you can post a new question with some example, it would be helpful – akrun Feb 07 '20 at 22:16
  • No. I upvoted on of your similar answer, and added a comment. – user5249203 Feb 07 '20 at 22:22