Wondering if anyone has run across a package/function in R that will combine levels of a factor whose proportion of all the levels in a factor is less than some threshold? Specifically, one of the first steps in data preparation I conduct is to collapse sparse levels of factors together (say into a level called 'Other') that do not constitute at least, say, 2% of the total. This is done unsupervised and is done when the objective is to model some activity in marketing (not fraud detection, where those very small occurrences could be extremely important). I am looking for a function that will collapse levels until some threshold proportion is met.
UPDATE:
Thanks to these great suggestions I wrote a function pretty easily. I did realize though that it was possible to collapse levels with proportion < the minimum and still have that recoded level be < the minimum, requiring the addition of the lowest level with proportion > the minimum. Likely can be more efficient but it appears to work. The next enhancement would be to figure out how to capture the "rules" for applying the collapse logic to new data (a validation set or future data).
collapseFactors<- function(tableName,minPercent=5,fillIn ="RECODED" )
{
for (i in 1:ncol(tableName))
{
if(is.factor(tableName[,i]) == TRUE) #process just factors
{
sortedTable<-sort(prop.table(table(tableName[,i])))
numberToCollapse<-length(sortedTable[sortedTable<(minPercent/100)])
if (sum(sortedTable[1:numberToCollapse])<(minPercent/100))
{
numberToCollapse=numberToCollapse+1 #add next level if < minPercent
}
if(numberToCollapse>1) #if not >1 then nothing to collapse
{
lf <- names(sortedTable[1:numberToCollapse])
levels(tableName[,i])[levels(tableName[,i]) %in% lf] <- fillIn
}
}#end if a factor
}#end for loop
return(tableName)
}#end function