tidyverse/forcats

fct_recode removes `label` attribute

iago-pssjd opened this issue · 4 comments

Hi!

fct_recode removes label attribute (and seems that it removes all the attributes). I expect it would not do (it may have sense that it removes a labels attribute, but not others).

Reprex:

library(haven)
library(forcats)
path <- system.file("examples", "iris.dta", package = "haven")
read_dta(path) |> str()
...
...
...
$ species    : chr [1:150] "setosa" "setosa" "setosa" "setosa" ...
  ..- attr(*, "label")= chr "Species"
  ..- attr(*, "format.stata")= chr "%10s"
# However
read_dta(path)$species |> fct_recode(seto = "setosa") |> str()
 Factor w/ 3 levels "seto","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
hadley commented

Could you please rework your reproducible example to use the reprex package ? That makes it easier to see both the input and the output, formatted in such a way that I can easily re-run in a local session.

@hadley done:

library(haven)
library(forcats)
path <- system.file("examples", "iris.dta", package = "haven")
t <- read_dta(path) 
t$species |> str()
#>  chr [1:150] "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" ...
#>  - attr(*, "label")= chr "Species"
#>  - attr(*, "format.stata")= chr "%10s"
t$species |> fct_recode(seto = "setosa") |> str()
#>  Factor w/ 3 levels "seto","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Created on 2023-10-31 with reprex v2.0.2

hadley commented

Thanks!

It seems this is not limited to fct_recode(), as I experience the same with most forcats functions.
This feature would be much appreciated by those like me that rely a lot on attributes like label.