[R] plot is not keeping the order of variable

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Feb 22 16:18:06 CET 2010


Dieter Menne wrote:
> 
> Peter Dalgaard wrote:
>> d <- data.frame(f=c("rare", "medium","well-done"))
>> #To get the cast in order of appearance, this can be used:
>>
>>  > d$f <- factor(d$f, levels=unique(d$f))
>>  > d$f
>> [1] rare      medium    well-done
>> Levels: rare medium well-done
>>
>>
> 
> .. which caused some head-scratching from me, because it made me believe
> there was some hidden Kopenhagen-factor conserving the original order.

> 
> To protect the innocent: for the more general case, unique() does not help.

Right. As I said, it gives "cast in order of appearance". The default 
factor levels are sort(unique(x)) which is independent of data order, 
but not necessarily desirable. In the general case, you have to tell R 
about the order explicitly.

> Dieter
> 
> levs = c("rare", "medium","well-done") 
> set.seed(4711)
> d <- data.frame(f=sample(levs,10,TRUE)) 
> unique(d$f)
> d$f =  factor(d$f, levels=unique(d$f)) 
> levels(d$f)
> d$f =  factor(d$f, levels = levs) 
> levels(d$f)
> 


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