Skip to content

Ordering the levels of a vector

4 messages · Judith Flores, Gabor Grothendieck, Deepayan Sarkar +1 more

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

Thank  you,

Judith








      ____________________________________________________________________________________
Be a better friend, newshound, and
#
Try mixedsort in the gtools package.
On Dec 3, 2007 4:21 PM, Judith Flores <juryef at yahoo.com> wrote:
#
On 12/3/07, Judith Flores <juryef at yahoo.com> wrote:
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
[1] Day -1 Day 6  Day 10
Levels: Day -1 Day 6 Day 10
-Deepayan
#
On Mon, 2007-12-03 at 13:21 -0800, Judith Flores wrote:
You could strip the 'Day' part of the elements using gsub(), sort the
numeric part and then paste() 'Day' back to the result:

set.seed(1)
day <- paste("Day", sample(-2:10))
[1] "Day 1"  "Day 2"  "Day 4"  "Day 7"  "Day -1" "Day 5"  "Day 8" 
 [8] "Day 10" "Day 3"  "Day -2" "Day 9"  "Day 0"  "Day 6" 

day.tmp <- sort(as.numeric(gsub("[^0-9\\-]", "", day)))
[1] -2 -1  0  1  2  3  4  5  6  7  8  9 10

day.levels <- paste("Day", day.tmp)
[1] "Day -2" "Day -1" "Day 0"  "Day 1"  "Day 2"  "Day 3"  "Day 4" 
 [8] "Day 5"  "Day 6"  "Day 7"  "Day 8"  "Day 9"  "Day 10"

day.ord <- factor(day, levels = day.levels)

# Note the order of the levels versus the order of the factor output
[1] Day 1  Day 2  Day 4  Day 7  Day -1 Day 5  Day 8  Day 10 Day 3 
[10] Day -2 Day 9  Day 0  Day 6 
13 Levels: Day -2 Day -1 Day 0 Day 1 Day 2 Day 3 Day 4 Day 5 ... Day 10


HTH,

Marc Schwartz