【问题标题】:Get labels as column values instead of numeric value获取标签作为列值而不是数值
【发布时间】:2021-05-04 15:26:37
【问题描述】:

我导入了一个 sav 文件,其中包含许多已标记的列。我想将标签作为值而不是标签数据。

library(tidyverse)
df <- structure(list(color = structure(c(1, 1, 1, 1, 2, 3, 2, 1, 1, 1), 
                                       label = "color", 
                                       format.spss = "F1.0", 
                                       labels = c(`blue` = 1, `yellow` = 2, `pink` = 3), 
                                       class = c("haven_labelled", "vctrs_vctr", "double"))), 
                row.names = c(NA,-10L), 
                class = c("tbl_df", "tbl", "data.frame"))

# color
# 1      1
# 2      1
# 3      1
# 4      1
# 5      2
# 6      3
# 7      2
# 8      1
# 9      1
# 10     1

我想得到什么

# color
# 1   blue
# 2   blue
# 3   blue
# 4   blue
# 5 yellow

我一直在寻找几个小时,但只能找到删除标签的方法,这会导致带有数值的 df 和标签完全消失(基本上是这篇文章中的第一个 df,没有标签信息)。有什么建议吗?

【问题讨论】:

    标签: r label


    【解决方案1】:

    也许haven::as_factor 是你需要的?

    它也适用于加载的核心 tidyverse 包,即 library(tidyverse) 并使用 as_factor 函数。我怀疑加载tidyverse 会从haven 安装函数,包括as_factor 函数。

    
    haven::as_factor(df)
    
    #> # A tibble: 10 x 1
    #>    color 
    #>    <fct> 
    #>  1 blue  
    #>  2 blue  
    #>  3 blue  
    #>  4 blue  
    #>  5 yellow
    #>  6 pink  
    #>  7 yellow
    #>  8 blue  
    #>  9 blue  
    #> 10 blue
    

    reprex package (v2.0.0) 于 2021-05-04 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多