tidyverse / forcats

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

It should not fail when lumping empty group with weight #294

Closed holgerbrandl closed 2 years ago

holgerbrandl commented 2 years ago

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)

xxspurs commented 2 years ago

您好,我已收到您的邮件,将尽快给您回复。

hadley commented 2 years ago

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