Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request: allow fct_lump to lump factors based on order of appearance #187

Open
dan-reznik opened this issue Mar 16, 2019 · 0 comments
Open
Labels
feature a feature request or enhancement wip work in progress

Comments

@dan-reznik
Copy link

dan-reznik commented Mar 16, 2019

While fct_lump() currently allows us to keep the N most frequent factors (lumping the rest into "Other"), I would love to have an option to this function (call it "inorder") which would instead preserve the first N factors, lumping the rest into "Other".

library(magrittr)
library(forcats)
f <- c("hello","goodbye","ciao","arrivederci","ciao","hello") %>% fct_inorder
f
#> [1] hello       goodbye     ciao        arrivederci
#> [5] ciao        hello      
#> Levels: hello goodbye ciao arrivederci

To preserve the first two appearing levels of the factor, create function fct_lump_inorder(), all other levels are lumped into "Other":

f %>% fct_lump_inorder(2)
#> [1] hello       goodbye     Other       Other
#> [5] Other        hello      
Levels: hello goodbye Other

Notice this is very useful if I have reordered a factor using fct_reorder() and now only want the first N of the list (akin to arrange() + head()). Example:

df %>%
   mutate(col1 = col1 %>% fct_reorder(-col2) %>% fct_lump_inorder(4)) %>%
   ggplot(aes(...)) + ....
@dan-reznik dan-reznik changed the title function request: fct_lump_inorder function request: allow fct_lump to lump factors based on order of appearance Mar 16, 2019
@dan-reznik dan-reznik changed the title function request: allow fct_lump to lump factors based on order of appearance request: allow fct_lump to lump factors based on order of appearance Mar 16, 2019
@hadley hadley added feature a feature request or enhancement wip work in progress labels Feb 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement wip work in progress
Projects
None yet
Development

No branches or pull requests

2 participants