rdiagnosticscontingencykappa

Sort a contingency table without changing table class


I want to reorder factors of cont.table

test.a <- c(rep(1,20),rep(0,40))
test.b <- c(rep(1,25),rep(0,35))

cont.table <- addmargins(table(test.a, test.b))

    test.b
test.a  0  1 Sum
   0   35  5  40
   1    0 20  20
   Sum 35 25  60

I want to be able to order the factors 0 and 1. The result I want is this

     1  0 Sum
1   20  0  20
0    5 35  40
Sum 25 35  60

I did it like this, but I lose the class Table, which is needed for me

> tbl <- as.data.frame.matrix(addmargins(table(test.a, test.b)))
> tbl2 <- cbind(tbl[2],tbl[1],tbl[3])
> tblfinal <- rbind(tbl2[2,],tbl2[1,],tbl2[3,])

> as.table(tblfinal)
Error in as.table.default(tblfinal) : cannot coerce to a table

Is there a possible way? the simpler the better


Solution

  • Make your test.x objects factors with a defined order, then the tables etc will be sorted appropriately. E.g.:

    test.a <- factor(test.a,levels=c(1,0))
    test.b <- factor(test.b,levels=c(1,0))
    addmargins(table(test.a,test.b))
    
    #      test.b
    #test.a  1  0 Sum
    #   1   20  0  20
    #   0    5 35  40
    #   Sum 25 35  60