[R] Re-ordering factors

maj at stats.waikato.ac.nz maj at stats.waikato.ac.nz
Sun Oct 7 10:38:49 CEST 2007


Thanks to James and Phil and Peter for their helpful suggestions. I think
that I should also point out one way *not* to do the job:

> xtabs(Count ~ Education + Age_Group, data=educ)
              Age_Group
Education        >64 25-34 35-44 45-54 55-64
  CompletedHS   7558 16431  1855  9435  8795
  IncompleteHS 13746  5416  5030  5777  7606
  Uni1-3        2503  8555  5576  3124  2524
  Uni4+         2483  9771  7596  3904  3109
> levels(educ$Education) <- c("IncompleteHS","CompletedHS",
+                           "Uni1-3","Uni4+")
> levels(educ$Age_Group) <- c("25-34","35-44","45-54","55-64",">64")
> xtabs(Count ~ Education + Age_Group, data=educ)
              Age_Group
Education      25-34 35-44 45-54 55-64   >64
  IncompleteHS  7558 16431  1855  9435  8795
  CompletedHS  13746  5416  5030  5777  7606
  Uni1-3        2503  8555  5576  3124  2524
  Uni4+         2483  9771  7596  3904  3109


Cheers,  Murray

> 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