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

Martin Maechler maechler at stat.math.ethz.ch
Thu Jan 22 16:29:37 CET 2015


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