Skip to content
Prev 199494 / 398502 Next

Counting non-empty levels of a factor

On Nov 8, 2009, at 8:38 AM, sylvain willart wrote:

            
Try:

result <- aggregate(MyData$brand , by=list(MyData$store) , length)

Quick, easy and generalizes to other situations. The factor levels got  
carried along identically, but length counts the number of elements in  
the list returned by tapply.
If you reapply the function, factor, you get the same result. So you  
could have done this:

 > result <- aggregate(MyData$brand , by=list(MyData$store) ,  
function(x) nlevels(factor(x)))
 > result
   Group.1 x
1       1 3
2       2 2
3       3 3
David Winsemius, MD
Heritage Laboratories
West Hartford, CT