After using table(A,B) in R, how can I order the columns and rows according to a particular ordering?

150 Views Asked by At

I am working in R and have tabulated two columns of a dataframe by using

table(A,B)

The final table, call it TAB has 4 x 4 columns. I want to order them based off some other ordering I came up with. The order from col1 - col4 I want is in vector called order.

Is there a way to reorder the columns and rows of TAB to be in the order of order?

TAB
   A  B   C  D 
A  6  0   1  2 
B  3  12  0  1
C  4  5   6  1
D  8  2   8  90

order = c('C','D','A','B')

Desired Output:

TABNew
   C  D   A  B 
C  6  1   4  5 
D  8  90  8  2
A  1  2   6  0
B  0  1   3  12
1

There are 1 best solutions below

0
On BEST ANSWER

So, in your case, sample input would be

dd<-data.frame(
    x=rep(LETTERS[1:4], c(9, 16, 16, 108)),
    y=rep(rep(LETTERS[1:4], 4), c(6, 0, 1, 2, 3,12,0,1,4,5,6,1,8,2,8,90))
)
myord<-c("C","D","A","B")

You can either sort after-the-fact

tt<-with(dd, table(x,y))
tt[myord, myord]

#      C  D  A  B
#   C  6  1  4  5
#   D  8 90  8  2
#   A  1  2  6  0
#   B  0  1  3 12

or you can set the order of the levels explicitly for each factor (which is what table() is counting up)

tt<-with(dd, table(factor(x, levels=myord),factor(y, levels=myord)))
tt

#      C  D  A  B
#   C  6  1  4  5
#   D  8 90  8  2
#   A  1  2  6  0
#   B  0  1  3 12

table will return values according to the order of the levels of the factor. (This is true of many other functions that use factors as well)