I want to combine all factors with a count less than n into one factor named \"Else\"
For example if n = 3 then in the following df I want to combine \"c\", \"d\" and \"
Why not something like this?
library(data.table)
dt <- data.table(df)
dt[,ynew := ifelse(.N < 3, "else",as.character(y)), by = "y"]
Another alternative:
#your dataframe
df = data.frame(x=c(1:10), y=c("a","a","a","b","b","b","c","d","d","e"))
#which levels to keep and which to change
res <- table(df$y)
notkeep <- names(res[res < 3])
keep <- names(res)[!names(res) %in% notkeep]
names(keep) <- keep
#set new levels
levels(df$y) <- c(keep, list("else" = notkeep))
df
# x y
#1 1 a
#2 2 a
#3 3 a
#4 4 b
#5 5 b
#6 6 b
#7 7 else
#8 8 else
#9 9 else
#10 10 else