[R] Retrieving Factors with Levels Ordered

Ben Bolker bbolker at gmail.com
Sat Jan 1 16:08:07 CET 2011


Berwin A Turlach <berwin <at> maths.uwa.edu.au> writes:

> 
> G'day H.T.
> 
> On Sat,  1 Jan 2011 00:41:10 -0500 (EST)
> "H. T. Reynolds" <htr <at> udel.edu> wrote:
> 
> > When I create a factor with labels in the order I want, write the
> > data as a text file, and then retrieve them, the factor levels are no
> > longer in the proper order.
> 
> Not surprisingly. :)
> 
> [..big snip..]
> > testdf <- read.table(file = 'Junkarea/test.txt')
> 

  Thanks to Berwin for the very thorough explanation.
At a more pragmatic level, I find that

testdf$myfactor <-
factor(testdf$myfactor,levels=unique(as.character(testdf$myfactor)))

  generally works OK to reorder the factor levels into the order in
which they appear in the data set ...



More information about the R-help mailing list