[R] Ordering the levels of a vector

Marc Schwartz marc_schwartz at comcast.net
Mon Dec 3 22:53:59 CET 2007


On Mon, 2007-12-03 at 13:21 -0800, 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')
>  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

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

> day
 [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)))

> day.tmp
 [1] -2 -1  0  1  2  3  4  5  6  7  8  9 10

day.levels <- paste("Day", day.tmp)

> day.levels
 [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
> day.ord
 [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



More information about the R-help mailing list