[R] Re-ordering factors

maj at stats.waikato.ac.nz maj at stats.waikato.ac.nz
Sun Oct 7 05:52:35 CEST 2007


A small example before I begin my query:

> educ <- read.table(efile, header=TRUE)
> educ
      Education Age_Group Count
1  IncompleteHS     25-34  5416
2  IncompleteHS     35-44  5030
3  IncompleteHS     45-54  5777
4  IncompleteHS     55-64  7606
5  IncompleteHS       >64 13746
6   CompletedHS     25-34 16431
7   CompletedHS     35-44  1855
8   CompletedHS     45-54  9435
9   CompletedHS     55-64  8795
10  CompletedHS       >64  7558
11       Uni1-3     25-34  8555
12       Uni1-3     35-44  5576
13       Uni1-3     45-54  3124
14       Uni1-3     55-64  2524
15       Uni1-3       >64  2503
16        Uni4+     25-34  9771
17        Uni4+     35-44  7596
18        Uni4+     45-54  3904
19        Uni4+     55-64  3109
20        Uni4+       >64  2483
> 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

Naturally I would prefer the factor levels in their natural ordering in
the table. I would like to re-order the levels of the factors to achieve
this.

I have tried reorder() in the gdata package:

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

which works on one factor but not the other.

I have fooled a bit with reorder.factor() but I can't seem to figure out
how to drive it!

Cheers,  Murray Jorgensen
-- 
Dr Murray Jorgensen      http://www.stats.waikato.ac.nz/Staff/maj.html
Department of Statistics, University of Waikato, Hamilton, New Zealand
Email: maj at waikato.ac.nz                                Fax 7 838 4155
Phone  +64 7 838 4773 wk    Home +64 7 825 0441    Mobile 021 1395 862



More information about the R-help mailing list