Skip to content
Prev 131156 / 398506 Next

Ordering the levels of a vector

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