Wednesday, October 3, 2007

Reorder factor levels

Very often, especially when plotting data, I need to reorder the levels of a factor because the default order is alphabetical. There must be many ways of reordering the levels; however, I always forget which package to look in. A direct way of reordering, using standard syntax is as follows:
## generate data
x = factor(sample(letters[1:5],100, replace=TRUE))

print(levels(x)) ## This will show the levels of x are "Levels: a b c d e"

## To reorder the levels:
## note, if x is not a factor use levels(factor(x))

x = factor(x,levels(x)[c(4,5,1:3)])

print(levels(x)) ## Now "Levels: d e a b c"
In this case, the level order could be set in the first line; however, if there are many levels (and you don't want to type out all of the levels explicitly), the above method is preferred. Again, if there is a better way to do this, please let me know in the comments.

1 comment:

Unknown said...

Thanks James! Vero led me to this today. Very useful for something that should be easier to figure out.

-Adrian