将Haven_labelled的向量标签提取为字符串向量

问题描述 投票:1回答:1

我有一个haven_labelled向量,我想从中提取其标签作为字符串向量:

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")不执行我想要的操作,因为它返回了一个命名向量:

#  one   two three 
#    1     2     3 

所需的输出:

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

我访问了很多文档,但无法找到解决方案,因此非常欢迎您的帮助!

r label r-haven
1个回答
2
投票

这是一个named向量,因此请使用names提取该向量的names

names(attr(vec, "labels"))
#[1] "one"   "two"   "three"
© www.soinside.com 2019 - 2024. All rights reserved.