# [R] Re-order levels of a categorical (factor) variable

Ravi Varadhan ravi.varadhan at jhu.edu
Thu Jan 22 16:49:50 CET 2015

```Dear Bert, Martin, Bill,

Thank you very much for the help.  Bert & Martin's solutions solved my problem.  Would it be useful to add an example like this to the help page on ?factor or ?levels?

Thanks again,
Ravi
________________________________________
From: Martin Maechler <maechler at stat.math.ethz.ch>
Sent: Thursday, January 22, 2015 10:29 AM
To: Bert Gunter
Cc: William Dunlap; r-help at r-project.org; Ravi Varadhan
Subject: Re: [R] Re-order levels of a categorical (factor) variable

>>>>> Bert Gunter <gunter.berton at gene.com>
>>>>>     on Wed, 21 Jan 2015 18:52:12 -0800 writes:

> Bill/Ravi:
> I believe the problem is that the factor is automatically created when
> a data frame is created by read.table(). By default, the levels are
> lexicographically ordered. The following reproduces the problem and
> gives a solution.

>> library(lattice)

>> z <- data.frame(y = 1:9, x = rep(c("pre", "day2","day10")))
>> xyplot(y~x,data=z) ## x axis order is day 10, day2, pre

>> levels(z\$x)
> [1] "day10" "day2"  "pre"

>> z\$x <- factor(as.character(z\$x),levels=c(levels(z\$x)[3:1])) ## explicitly defines level order
>> xyplot(y~x,data=z) ##  desired plot

Indeed, thank you, Bert,
and using  levels(.) <- *   does *not* work... (as I first thought).

However, slightly shorter and easier and maybe even easier to remember than

z\$x <- factor(as.character(z\$x), levels = c(levels(z\$x)[3:1])) ## def. level order

is

z\$x <- factor(z\$x, levels = levels(z\$x)[3:1])   ## def. level order

Martin Maechler, ETH Zurich

```

More information about the R-help mailing list