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

Feature suggestion: fct_others that move all non given levels to other #40

Closed
lepennec opened this Issue Sep 23, 2016 · 2 comments

Comments

Projects
None yet
2 participants
@lepennec
Copy link

lepennec commented Sep 23, 2016

I often have to recode with a lot of not interesting levels that I want to replace by a single "Others" one. Because I'm lazy, I would like to give only the levels I want to keep...

I've made a prototype which does the job:

fct_others <- function(f, ..., other_level = "Others") {
  f <- forcats:::check_factor(f)
  levels <- levels(f)
  new_levels <- if_else(levels %in% list(...), levels, other_level)
  f <- lvls_revalue(f, new_levels)

  # Place other at end
  levels <- levels(f)
  other_back <- c(setdiff(levels, other_level), intersect(levels, other_level))
  lvls_reorder(f, match(other_back, levels))
}

@hadley hadley closed this in 89d23ca Jan 19, 2017

@hadley

This comment has been minimized.

Copy link
Member

hadley commented Jan 19, 2017

I took a slightly more verbose & general approach. I think the explicit keep and drop arguments will also make it slightly easier to guess at what fct_other() does when re-reading code.

@lepennec

This comment has been minimized.

Copy link

lepennec commented Jan 19, 2017

It's indeed much better! Thanks for your tremendous job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment