tidyverse/forcats

Allow forcats to support integer and numeric inputs

billdenney opened this issue · 1 comments

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

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.