Manually replace levels with "other"

fct_other(f, keep, drop, other_level = "Other")

Arguments

f

A factor (or character vector).

keep, drop

Pick one of keep and drop:

  • keep will preserve listed levels, replacing all others with other_level.

  • drop will replace listed levels with other_level, keeping all as is.

other_level

Value of level used for "other" values. Always placed at end of levels.

See also

fct_lump() to automatically convert the rarest (or most common) levels to "other".

Examples

x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))

fct_other(x, keep = c("A", "B"))
#>  [1] A     A     A     A     A     A     A     A     A     A     A     A    
#> [13] A     A     A     A     A     A     A     A     A     A     A     A    
#> [25] A     A     A     A     A     A     A     A     A     A     A     A    
#> [37] A     A     A     A     B     B     B     B     B     B     B     B    
#> [49] B     B     Other Other Other Other Other Other Other Other Other Other
#> [61] Other Other Other Other Other Other Other Other Other Other Other Other
#> [73] Other Other Other Other Other Other Other Other Other Other Other Other
#> [85] Other Other Other
#> Levels: A B Other
fct_other(x, drop = c("A", "B"))
#>  [1] Other Other Other Other Other Other Other Other Other Other Other Other
#> [13] Other Other Other Other Other Other Other Other Other Other Other Other
#> [25] Other Other Other Other Other Other Other Other Other Other Other Other
#> [37] Other Other Other Other Other Other Other Other Other Other Other Other
#> [49] Other Other C     C     C     C     C     D     D     D     D     D    
#> [61] D     D     D     D     D     D     D     D     D     D     D     D    
#> [73] D     D     D     D     D     D     D     D     D     D     E     F    
#> [85] G     H     I    
#> Levels: C D E F G H I Other