codebook icon indicating copy to clipboard operation
codebook copied to clipboard

Value labels not displayed for `haven_labelled` `character`

Open maia-sh opened this issue 5 years ago • 0 comments

Thank you for this wonderful package!

I am trying to use value labels for a character vector within a codebook.

I expect the labels to appear in the codebook under the "Value labels" tab as name. This works for haven_labelled double (df_labelled$number), but does not work for a haven_labelled character (df_labelled$color). A workaround is to change the haven_labelled character to factors (df_labelled$color_fac) which then display the labels instead under the "Summary statistics" tab as value_labels.

It would be great to have the value label show up in the same format for character vectors as it does for double vectors.

library(dplyr)
library(labelled)
library(codebook)

df <- tribble(
  ~id, ~letter, ~color, ~number,
  1, "a", "blue", 21,
  1, "a", "red", 36,
  1, "b", "blue", 15,
  2, "c", "red", 27,
  2, "d", "purple", 28
)

df_labelled <-
  df %>% 
  
  labelled::set_variable_labels(
    id = "Unique identifier",
    letter = "The letter",
    color = "The color",
    number = "The number"
  ) %>% 
  
  labelled::set_value_labels(
    letter = c(
      Apple = "a",
      Banana = "b",
      Carrot = "c",
      Date = "d"
    ),
    color = c(
      `Rockin' Red` = "red",
      `Blastin' Blue` = "blue",
      `Pumpin' Purple` = "purple"
    ),
    number = c(
      `twenty-one` = 21,
      `thirty-six` = 36,
      `fifteen` = 15,
      `twenty-seven` = 27,
      `twenty-eight` = 28
    )
  ) %>% 
  
  mutate(color_fac = labelled::to_factor(color))

attributes(df_labelled$color)
#> $labels
#>    Rockin' Red  Blastin' Blue Pumpin' Purple 
#>          "red"         "blue"       "purple" 
#> 
#> $label
#> [1] "The color"
#> 
#> $class
#> [1] "haven_labelled" "vctrs_vctr"     "character"
attributes(df_labelled$number)
#> $labels
#>   twenty-one   thirty-six      fifteen twenty-seven twenty-eight 
#>           21           36           15           27           28 
#> 
#> $label
#> [1] "The number"
#> 
#> $class
#> [1] "haven_labelled" "vctrs_vctr"     "double"
attributes(df_labelled$color_fac)
#> $levels
#> [1] "Rockin' Red"    "Blastin' Blue"  "Pumpin' Purple"
#> 
#> $class
#> [1] "factor"
#> 
#> $label
#> [1] "The color"

# codebook::codebook(df_labelled)

Created on 2021-01-26 by the reprex package (v0.3.0)

maia-sh avatar Jan 26 '21 17:01 maia-sh