forcats icon indicating copy to clipboard operation
forcats copied to clipboard

fct_inorder fails if factor contains empty levels

Open jwilliman opened this issue 5 years ago • 2 comments

Running forcats::fct_inorder on factors with empty levels produces an (informative) error.

Is this behaviour expected/desired, or should empty levels be automatically dropped (with a warning)? If expected, would be good to flag on the help file.


library(forcats)
f <- factor(rev(letters[1:5]), levels = letters[1:6])
fct_inorder(f)
#> Error: `idx` must contain one integer for each level of `f`
fct_infreq(f)
#> [1] e d c b a
#> Levels: a b c d e f
fct_inorder(fct_drop(f))
#> [1] e d c b a
#> Levels: e d c b a

Created on 2020-04-29 by the reprex package (v0.3.0)

jwilliman avatar Apr 29 '20 04:04 jwilliman

Hmmm, given that the levels don't appear in the data, what do you expect fct_inorder() to do with them? Put them at the end? Drop them?

hadley avatar Dec 09 '20 14:12 hadley

Put them at the end makes the most sense to me, as you may want them for zero counts in tables etc. You also have more flexibility keeping them, as you can simply run fct_drop if you don't want them, but if the default is to drop the levels then it is harder to add them back should you want them.

jwilliman avatar Mar 31 '21 03:03 jwilliman