larmarange / labelled

Manipulating labelled vectors in R
https://larmarange.github.io/labelled/
GNU General Public License v3.0
73 stars 16 forks source link

Feature request: could `set_value_labels` work on a variable of class factor? #160

Closed davidhodge931 closed 4 months ago

davidhodge931 commented 4 months ago

Incredible package, thanks!

I'm just getting started labelling, so apologies if this is a dumb request.

Was wondering if it was possible to set_value_labels on a variable of class factor?

library(palmerpenguins)
library(labelled)
library(tidyverse)

#does not work
penguins |>
  set_value_labels(sex = c(Female = "female", Male = "male"))
#> Error in `val_labels<-.factor`(`*tmp*`, null_action = .null_action, value = values[[v]]): Value labels cannot be applied to factors.

#only works if convert to character
penguins |>
  mutate(sex = as.character(sex)) |> 
  set_value_labels(sex = c(Female = "female", Male = "male")) |> 
  select(sex) |> 
  head()
#> # A tibble: 6 × 1
#>   sex            
#>   <chr+lbl>      
#> 1 male [Male]    
#> 2 female [Female]
#> 3 female [Female]
#> 4 <NA>           
#> 5 female [Female]
#> 6 male [Male]

Created on 2024-05-06 with reprex v2.1.0

larmarange commented 4 months ago

By definition, haven_labelled class could be applied only to numeric or character vectors. Labelled vectors are an alternative to factors. You could transform labelled vectors to factors or factors to labelled vectors. But there is no point to add value labels to factors.