Dieter Menne wrote:
Peter Dalgaard wrote:
d <- data.frame(f=c("rare", "medium","well-done"))
#To get the cast in order of appearance, this can be used:
> d$f <- factor(d$f, levels=unique(d$f))
> d$f
[1] rare medium well-done
Levels: rare medium well-done
.. which caused some head-scratching from me, because it made me believe
there was some hidden Kopenhagen-factor conserving the original order.
To protect the innocent: for the more general case, unique() does not help.
Right. As I said, it gives "cast in order of appearance". The default
factor levels are sort(unique(x)) which is independent of data order,
but not necessarily desirable. In the general case, you have to tell R
about the order explicitly.
Dieter
levs = c("rare", "medium","well-done")
set.seed(4711)
d <- data.frame(f=sample(levs,10,TRUE))
unique(d$f)
d$f = factor(d$f, levels=unique(d$f))
levels(d$f)
d$f = factor(d$f, levels = levs)
levels(d$f)
--
O__ ---- Peter Dalgaard Ă˜ster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalga...@biostat.ku.dk) FAX: (+45) 35327907
______________________________________________
R-help@r-project.org 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.