Re: [R] Ordering the levels of a vector

From: Deepayan Sarkar <>
Date: Mon, 3 Dec 2007 13:42:15 -0800

On 12/3/07, Judith Flores <> wrote:
> Hi,
> I have a vector in a data frame that looks
> something like this:
> day<-c('Day -1','Day 6','Day 10')
> This vector specifies the order in which several
> panel will appear in a lattice plots. But the order in
> which such plots will appear will be the following:
> Day -1, Day 10, Day 6. Which makes sense, but I cannot
> name the Days like this: Day -01,Day 10, Day 06, which
> would put the levels in the order I want them to be.
> Now, this vector won't always have the same values,
> it could be:
> day<-c('Day -1, 'Day 2','Day 14')
> So I cannot set the levels manually:
> levels(day)<-c('Day -1', 'Day something','Day
> something else')

Well, you need some sort of rule that can be used to determine the order of the levels. The default (see ?factor) is 'levels = sort(unique(x))'. If you instead want, say, levels in the order of first appearance (assuming that's what you mean by "original order"), you could define

my.factor = function(x) { factor(x, levels = unique(x)) }

and then use

> day<- my.factor(c('Day -1','Day 6','Day 10'))
> day

[1] Day -1 Day 6 Day 10
Levels: Day -1 Day 6 Day 10

> I tried as.ordered, but I guess I am not using the
> right function.
> How can I command the script to put the panels in the
> original order given of the vector in a data frame?

-Deepayan mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Mon 03 Dec 2007 - 21:58:26 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 03 Dec 2007 - 22:30:16 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.