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 <maech...@stat.math.ethz.ch>
Sent: Thursday, January 22, 2015 10:29 AM
To: Bert Gunter
Cc: William Dunlap; r-help@r-project.org; Ravi Varadhan
Subject: Re: [R] Re-order levels of a categorical (factor) variable

>>>>> Bert Gunter <gunter.ber...@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


______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to