[R] sort table

Marc Schwartz MSchwartz at mn.rr.com
Sat Nov 5 18:44:27 CET 2005


On Sat, 2005-11-05 at 18:04 +0100, Claus Atzenbeck wrote:
> Hi,
> 
> I have a data frame named "questions" that I use to get a subset and
> then a table:
> 
> failcondonly <- subset(questions, errorreason=="condition")
> failcondtab <- table(failcondonly$type, failcondonly$qid, exclude=c("ORGA", "skipped"))
> 
> The failcondtab looks like this:
> 
>         6 11 12 13 14 15 17 26 30 31 39 41
> gave up 0  1  1  1  1  0  0  0  0  8  0  2
> wrong   3  3  7  3  3  1  4  1  3  4  1  2
> 
> I want to sort this table according to the *sum* of the values in "gave
> up" and "wrong" in reverse order. The highest value should be first.
> First would be column "31" (value 8+4=12), then column "12" (value
> 1+7=8), etc.
> 
> sort(failcondtab) does not help, since it sorts the column names, not
> the sum of the values of each column.
> 
> Thanks for any hint.
> Claus


Something like the following should work:

> failcondtab[, rev(order(colSums(failcondtab)))]
        31 12 41 17 14 13 11 30 6 39 26 15
gave up  8  1  2  0  1  1  1  0 0  0  0  0
wrong    4  7  2  4  3  3  3  3 3  1  1  1


See ?order, ?rev and ?colSums.

HTH,

Marc Schwartz




More information about the R-help mailing list