Skip to content
Prev 198766 / 398506 Next

Collapse factor levels

Kevin E. Thorpe wrote:
It's an anomaly inherited frokm S-PLUS (or so I have been told). 
Actually, with the current R, you should get a warning:

 > x <- 1:10
 > 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

This works (as documented on the help page for levels!):

 > x <- 1:10
 > x <- factor(x,levels=1:10)
 > levels(x) <- c("A","A","A","B","B","B","C","C","C","C")
 > table(x)
x
A B C
3 3 4