Skip to content

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

@lepennec

Description

@lepennec

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))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions