Most frequent factor in R



I wanted to know how to obtain the most frequent factor in R if the vector is as below:

DT = c(‘a’,‘b’,‘c’,‘a’,‘a’,‘a’,‘b’,‘c’,‘c’,‘c’,‘c’,‘c’)
DT = as.factor(DT)



this could help perhaps. Simple enter a vector and it give you a data frame with count and frequency


------ For factor variables

Input: A vector which could be a factor

Output: One list with the information

- Number of values

- Number of levels

- data frame with levels absolute number of values, density of values

( you can use as.matrix() and then data.frame()

to build a column)

if( class(somefactor) !=“factor”){
somefactor <-factor(somefactor)
# More than 100 levels does not make sense
numberlevels <-length(levels(somefactor))
if(numberlevels > 1000){
stop(“More than 1000 levels \n”)
numbervalues <-length(somefactor)
temp <-replicate(length(somefactor), c(1))
results <- by(temp, somefactor, sum, simplify = TRUE)
results <- data.frame(Factors= attributes(results)$dimnames$somefactor,
Observations = as.vector(results),
stringsAsFactors = FALSE)
reldensity <-sapply(results$Observations,
function(x) {x/numbervalues})
results <-cbind(results, Density= reldensity )
back <-list(values= numbervalues, numblevels=numberlevels, frequency = results)