tidyverse/forcats

It should not fail when lumping empty group with weight

holgerbrandl opened this issue · 2 comments

When using fct_lump on a grouped data frame with a weighting attribute, it should not fail if a group is empty.

Example

iris %>% 
  group_by(Species) %>% filter(Species == "virginica") %>% 
  mutate(Species_Lumped = forcats::fct_lump(Species, w = Speal.Length, prop = 0.04))

This fails using v0.5.1 with

Error: Problem with `mutate()` column `Species_Lumped`.
i `Species_Lumped = forcats::fct_lump(Species, w = Sepal.Length, prop = 0.04)`.
x missing value where TRUE/FALSE needed
i The error occurred in group 1: Species = virginica.
Run `rlang::last_error()` to see where the error occurred

Tested with R version 4.1.2 (2021-11-01)

Reprex:

library(dplyr, warn.conflicts = FALSE)

iris %>% 
  group_by(Species) %>% 
  filter(Species == "virginica") %>% 
  mutate(Species_Lumped = forcats::fct_lump(Species, w = Sepal.Length, prop = 0.04))
#> Error in `mutate()`:
#> ! Problem while computing `Species_Lumped = forcats::fct_lump(Species, w
#>   = Sepal.Length, prop = 0.04)`.
#> ℹ The error occurred in group 1: Species = virginica.
#> Caused by error in `if (prop > 0 && sum(prop_n <= prop) <= 1) ...`:
#> ! missing value where TRUE/FALSE needed

Created on 2022-03-02 by the reprex package (v2.0.1)

Duplicate of #292