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
So, in your case, sample input would be
You can either sort after-the-fact
or you can set the order of the levels explicitly for each factor (which is what
table()
is counting up)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)