2

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
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90
  • 1
    Please take the time to create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. This would make it much easier to see the problem and provide a specific solution. – MrFlick Dec 08 '14 at 22:59
  • Are you just referring to the arrangement of columns? This should just work like matrix subsetting, i.e. `TAB[, order]`. – konvas Dec 08 '14 at 23:03
  • Done, konvas, the rows have to change accordingly in the crosstab – wolfsatthedoor Dec 08 '14 at 23:07
  • 1
    So `TAB[order, order]`? (btw to be reproducible you need to show `A` and `B` or `dput(TAB)`) – konvas Dec 08 '14 at 23:15

1 Answers1

4

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)

MrFlick
  • 195,160
  • 17
  • 277
  • 295