tidyverse / forcats

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

Allow forcats to support integer and numeric inputs #324

Closed billdenney closed 1 year ago

billdenney commented 1 year ago

Base R appears to convert integer and numeric inputs to character before making them factors. I think that similar functionality would be helpful in forcats. In the example below, my request is that both the integer and numeric input methods succeed:

forcats::fct_inorder(1:5)
#> Error in `forcats::fct_inorder()`:
#> ! `f` must be a factor or character vector, not an integer vector

#> Backtrace:
#>     ▆
#>  1. └─forcats::fct_inorder(1:5)
#>  2.   └─forcats:::check_factor(f)
#>  3.     └─cli::cli_abort(...)
#>  4.       └─rlang::abort(...)
forcats::fct_inorder(as.numeric(1:5))
#> Error in `forcats::fct_inorder()`:
#> ! `f` must be a factor or character vector, not a numeric vector

#> Backtrace:
#>     ▆
#>  1. └─forcats::fct_inorder(as.numeric(1:5))
#>  2.   └─forcats:::check_factor(f)
#>  3.     └─cli::cli_abort(...)
#>  4.       └─rlang::abort(...)
factor(1:5)
#> [1] 1 2 3 4 5
#> Levels: 1 2 3 4 5

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

hadley commented 1 year ago

One of the design principles of forcats is to be strict about inputs in order to avoid silently propagating mistakes. Adding an as.character() is only a small amount of extra code and it makes it very clear that you're deliberately turning numbers into factors.