Skip to content
Back to formatted view

Raw Message

Message-ID: <48BC03FC.4080803@biostat.ku.dk>
Date: 2008-09-01T15:02:20Z
From: Peter Dalgaard
Subject: ordered factor and table
In-Reply-To: <48BBF66B.8070002@gvdnet.dk>

Troels Ring wrote:
> dear friends - I have an ordered factor, ID, in a data.frame, labs,
> and make a table,
> aa <- with(labs,table(val >150,ID)) - and now the order in the table
> is according to the alphabetic order in ID, and not as I want it. I
> have tried adding
> [order(unique(labs$ID)] but it doesn't help.
> I have R 2.7.1 on WinXP.   

Hi Troels,

I suspect that your notion of "ordered factor" differs from the
technical one. Is the issue that you want ID to have the ordering of
levels as the order of appearance in your data? In that case, try
something like


within(labs, ID <- factor(ID, levels=unique(ID)))


As in:

> x <- c("Crosby","Stills","Nash","Nash","Young")
> ID <- factor(x)
> ID
[1] Crosby Stills Nash   Nash   Young
Levels: Crosby Nash Stills Young
> ID <- factor(ID, levels=unique(ID))
> ID
[1] Crosby Stills Nash   Nash   Young
Levels: Crosby Stills Nash Young
> table(ID)
ID
Crosby Stills   Nash  Young
     1      1      2      1


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