[R] Factor levels.

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Oct 3 07:48:30 CEST 2007


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?)

The canonical way is

factor(fff, levels=c("Unit", "Achieved", "Scholarship"), 
labels=c("U","A","S"))
> Is there a sexier way?
>
> 			cheers,
>
> 				Rolf Turner
>   


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list