[R] Custom Sort on a Table object

Bill.Venables at csiro.au Bill.Venables at csiro.au
Tue Jun 7 05:38:47 CEST 2011


Here is a one way.

> tab
                    f        m
0 to 5      11.328000 6.900901
15 to 24     6.100570 5.190058
25 to 34     9.428707 6.567280
35 to 44    10.462158 7.513270
45 to 54     7.621988 5.692905
5 to 14      6.502741 6.119663
55 to 64     5.884737 4.319905
65 to 74     5.075606 4.267810
75 to 84     4.702020 3.602362
85 and_over  4.750000 3.877551
> 
> lowAge <- as.numeric(sapply(strsplit(rownames(tab)," "), "[", 1))
> (tab <- tab[order(lowAge), ])
                    f        m
0 to 5      11.328000 6.900901
5 to 14      6.502741 6.119663
15 to 24     6.100570 5.190058
25 to 34     9.428707 6.567280
35 to 44    10.462158 7.513270
45 to 54     7.621988 5.692905
55 to 64     5.884737 4.319905
65 to 74     5.075606 4.267810
75 to 84     4.702020 3.602362
85 and over  4.750000 3.877551
>  

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Galen Moore
Sent: Tuesday, 7 June 2011 1:23 PM
To: r-help at r-project.org
Subject: [R] Custom Sort on a Table object

Greetings - 

 

I've got the following table (the result of a two-way table operation):

 

                      f         m

  0 to 5      11.328000  6.900901

  15 to 24     6.100570  5.190058

  25 to 34     9.428707  6.567280

  35 to 44    10.462158  7.513270

  45 to 54     7.621988  5.692905

  5 to 14      6.502741  6.119663

  55 to 64     5.884737  4.319905

  65 to 74     5.075606  4.267810

  75 to 84     4.702020  3.602362

  85 and over  4.750000  3.877551

 

Which I'd like to sort so that the column of rownames (which represent age
bands) and their corresponding f and m values appear in logical order.  I've
tried a bunch of things; merging with a separate df bearing Age Bands paired
with a sequence number, stripping out row vectors and rbind-ing a new df,
etc., all to no avail.  It seems to be very difficult to spin a table object
into a data frame without being stuck with the tables rownames!

 

I haven't yet tried writing to an external file and then reading it back (so
as to get R to forget that it's a Table object), and then merging on the
group bands to pull in a sequence vector upon which to do an order().  Seems
like it should be easier. 

 

Many thanks,

 

Galen 


	[[alternative HTML version deleted]]

______________________________________________
R-help at 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.



More information about the R-help mailing list