[R] Factor levels

Gabor Grothendieck ggrothendieck at gmail.com
Tue Aug 28 20:03:35 CEST 2007


You can create your own class and pass that to read table.  In
the example below Fld2 is read in with factor levels C, A, B
in that order.


library(methods)
setClass("my.levels")
setAs("character", "my.levels",
  function(from) factor(from, levels = c("C", "A", "B")))


### test ###

Input <- "Fld1 Fld2
10 A
20 B
30 C
40 A
"
DF <- read.table(textConnection(Input), header = TRUE,
  colClasses = c("numeric", "my.levels"))
str(DF)
# or
DF <- read.table(textConnection(Input), header = TRUE,
  colClasses = list(Fld2 = "my.levels"))
str(DF)


On 8/28/07, Sébastien <pomchip at free.fr> wrote:
> Dear R-users,
>
> I have found this not-so-recent post in the archives  -
> http://tolstoy.newcastle.edu.au/R/devel/00a/0291.html - while I was
> looking for a particular way to reorder factor levels. The question
> addressed by the author was to know if the read.table function could be
> modified to order the levels of newly created factors "according to the
> order that they appear in the data file". Exactly what I am looking for.
> As there was no reply to this post, I wonder if any move have been made
> towards the implementation of this suggestion. A quick look at
> ?read.table tells me that if this option was implemented, it was not in
> the read.table function...
>
> Sebastien
>
> PS: I am sorry to post so many messages on the list, but I am learning R
> (basically by trials & errors ;-) ) and no one around me has even a
> slight notion about it...
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> 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.
>



More information about the R-help mailing list