tidyverse / forcats

🐈🐈🐈🐈: tools for working with categorical variables (factors)
https://forcats.tidyverse.org/
Other
553 stars 126 forks source link

`fct()` doesn't work on factors #323

Closed DanChaltiel closed 1 year ago

DanChaltiel commented 1 year ago

Hi,

Like its old cousin factor(), it would be nice if fct() could be useful on factors too. For instance, I would expect this to work with fct() (although I know I could do it with fct_expand()):

factor("a", levels=c("a", "b"))
#> [1] a
#> Levels: a b
factor("a", levels=c("a", "b")) %>% factor(levels=c("a", "b", "c"))
#> [1] a
#> Levels: a b c

In fact, when dealing with tables containing character and factor columns, it can happen to be very useful to be able to use fct() on both indifferently.

However, using fct() on factors will throw an error (unlike factor()):

a = factor("a")
factor(a)
#> [1] a
#> Levels: a
forcats::fct(a)
#> Error in `forcats::fct()`:
#> ! `x` must be a character vector

Created on 2022-12-02 with reprex v2.0.2

Even on factors, fct() would keep its loved advantages over factor(), such as preserving attributes.

hadley commented 1 year ago

I think this is probably a good idea, but I don't think it would preserve attributes; fct() is a constructor not a coercer.

hadley commented 1 year ago

I've changed my mind: I think fct() is basically a constructor function; and it should only work with character vectors.