[R] Ordering the levels of a vector

Deepayan Sarkar deepayan.sarkar at gmail.com
Mon Dec 3 22:42:15 CET 2007


On 12/3/07, Judith Flores <juryef at yahoo.com> 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



More information about the R-help mailing list