Skip to content
Prev 198765 / 398506 Next

Collapse factor levels

On Nov 1, 2009, at 3:51 PM, Kevin E. Thorpe wrote:

            
You have thusly created a pathological situation. In 2.10.0 this is  
what you might see:

 >  x <-  
factor(x,levels=1:10,labels=c("A","A","A","B","B","B","C","C","C","C"))
Warning message:
In `levels<-`(`*tmp*`, value = c("A", "A", "A", "B", "B", "B", "C",  :
   duplicated levels will not be allowed in factors anymore

What you _should_ have done was:

  x2 <- factor(c("A","A","A","B","B","B","C","C","C","C"))

The usual approach to getting rid of unused factor levels is just to  
apply the function factor() again without additional arguments.

 > x <- factor(x)  # the "x" was from your code
Warning message:
In `levels<-`(`*tmp*`, value = c("A", "A", "A", "B", "B", "B", "C",  :
   duplicated levels will not be allowed in factors anymore

# but that will be the last time you will see the warning..

 > summary(x)
A B C
3 3 4