How to find the category with the least observations in a table?

Question:

Suppose you have the following data:

a<-c(rep("agosto",3),rep("janeiro",4),rep("maio",6))
table(a)

Want to know which month with the least observations?

With the min(table(a)) the answer is the minimum value and not the month with the fewest observations.

If you use the which.min() function you get the following result.

> which.min(table(a))
agosto 
     1 

But what I need is to return only the category.

Answer:

You can only get the names attribute from which.min :

a<-c(rep("agosto",3),rep("janeiro",4),rep("maio",6))
tabela<-table(a)
names(which.min(tabela))
[1] "agosto"

To understand better, when you put which.min(tabela) you generate a vector with a name attribute:

str(which.min(tabela))
 Named int 1
 - attr(*, "names")= chr "agosto"

So if you want to get just the name(s) of the vector, you use the names function. Another way to do the same thing is attr(which.min(tabela), "names")

Scroll to Top