forcats icon indicating copy to clipboard operation
forcats copied to clipboard

fct_recode removes `label` attribute

Open iagogv3 opened this issue 2 years ago • 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 ...

iagogv3 avatar Feb 21 '23 07:02 iagogv3

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 avatar Oct 31 '23 17:10 hadley

@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

iagogv3 avatar Oct 31 '23 22:10 iagogv3

Thanks!

hadley avatar Oct 31 '23 22:10 hadley

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.

DanChaltiel avatar Jun 06 '24 14:06 DanChaltiel