[R] Re-ordering factors
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Sun Oct 7 09:49:15 CEST 2007
James Reilly wrote:
> Using reorder.factor from the stats package seems to work:
>
> educ$ed <- reorder(educ$Education, sort(rep(1:4,5)))
> levels(educ$Education)
> [1] "CompletedHS" "IncompleteHS" "Uni1-3" "Uni4+"
> levels(educ$ed)
> [1] "IncompleteHS" "CompletedHS" "Uni1-3" "Uni4+"
> xtabs(Count ~ ed + Age_Group, data=educ)
> Age_Group
> ed 25-34 35-44 45-54 55-64 >64
> IncompleteHS 5416 5030 5777 7606 13746
> CompletedHS 16431 1855 9435 8795 7558
> Uni1-3 8555 5576 3124 2524 2503
> Uni4+ 9771 7596 3904 3109 2483
>
Notice that factor() itself will do it quite happily:
ed <- factor(Education, levels = c("IncompleteHS", "CompletedHS", "Uni1-3", "Uni4+"))
or even, utilizing the fact that the levels were in the right order to begin with
> educ$Education <- factor(educ$Education, levels=unique(educ$Education))
> educ$Age_Group <- factor(educ$Age_Group, levels=unique(educ$Age_Group))
> xtabs(Count ~ Education + Age_Group, data=educ)
Age_Group
Education 25-34 35-44 45-54 55-64 >64
IncompleteHS 5416 5030 5777 7606 13746
CompletedHS 16431 1855 9435 8795 7558
Uni1-3 8555 5576 3124 2524 2503
Uni4+ 9771 7596 3904 3109 2483
--
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.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list