On 3/10/2007, at 5:48 PM, Peter Dalgaard wrote: > Rolf Turner wrote: >> I have factors with levels ``Unit", "Achieved", and "Scholarship"; >> I wish to replace these with >> "U", "A", and "S". >> >> So I do >> >> fff <- factor(fff,labels=c("U","A","S")) >> >> This works as long as all of the levels are actually present in >> the factor. But if ``Scholarship'' is absent >> (as if often is) then I get an error. >> >> I can do a workaround such as >> >> fff <- factor(c("U","A","S")[fff],levels=c("U","A","S")) >> >> but this seems kludgy to me. >> > Does it even work? (What if it is the first or the 2nd level that > is absent?
Yes it works. What's the problem? To beat it to death: if the second level of fff is absent then fff will consist entirely of 1's and 3's, and so c("U","A","S")[fff] will consist entirely of U's and S's. I can then set the levels to be c("U","A","S") and get what I want. Note that if I just did fff <- factor(c("U","A","S")[fff]) in these circumstances, then I would get a factor whose levels were c ("U","S") which is NOT what I want. (I.e. I want the levels always to be c("U","A","S") irrespective of what levels are actually present in the factor.) > The canonical way is > > factor(fff, levels=c("Unit", "Achieved", "Scholarship"), labels=c > ("U","A","S")) Right. That is indeed sexier. Thanks. cheers, Rolf ###################################################################### Attention:\ This e-mail message is privileged and confidenti...{{dropped}} ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.