Q:

Reduce to 53 class in column R

I have column in dataset with 66 class. I want to reduce to 53 class where top 52 class will have their name and for rest I want to set as 'Others'. I was able to find top 52 class with most frequency but I'm not sure how can I set 'Others' to rest 14 class.
Column:
dept Att Jon_sat
 A    Y    2
 C    N    1
 D    N    4
 .    .    .
 .    .    .
 AB   N    3

data %>%
  group_by(dept) %>%
  summarise(n()) %>%
  top_n(53)

A:

We could use fct_lump_n from forcats
library(dplyr)
library(forcats)
data %>%
    mutate(dept = fct_lump_n(dept, n = 52))
#     dept
#1      s
#2     TT
#3      H
#4      I
#5      C
#6      j
#7     DD
#8     BB
#9     UU
#10     h
#11    DD
#12 Other
#13     h
#14 Other
#15     K
#16     u
#17 Other
#18     u
#19     h
#20    XX
#...

If we use the OP's method, one option is to replace the original 'dept' based on the values in 'dept'  extracted after the top_n
d1 <- data %>%
    group_by(dept) %>%
    summarise(n()) %>%
    top_n(53) %>%
    pull(dept)
data %>%
    mutate(dept = replace(dept, !dept %in% d1, 'Others'))

data
set.seed(24)
data <- data.frame(dept = sample(c(letters, LETTERS, paste0(LETTERS, LETTERS)),
        500, replace = TRUE), stringsAsFactors = FALSE)

