Sorting descending or ascending a column based on another column in R

Lets start with typical sorting. Sorting a table in R is fairly straight forward.

sample data (tbl)

ID SUB ID Value
A sub_3 55.28
C sub_3 55.89
A sub_3 56.61
B sub_3 56.67
A sub_3 59.01
C sub_3 63.71
C sub_4 41.06
D sub_4 42.43
C sub_4 43.07
A sub_4 43.29
D sub_4 53.56
C sub_4 53.61
C sub_4 53.93
D sub_4 55.06
D sub_4 55.62
B sub_5 54.9
B sub_5 55.92
B sub_5 55.94
D sub_5 56.78
C sub_5 56.91
D sub_5 59.65
B sub_5 60.01
C sub_6 35.08
D sub_6 37.03
D sub_6 40.97
C sub_6 41.68
C sub_6 43.49
D sub_6 45.92


Lets sort by column 'Value'.

Attach the table.
> attach(tbl)


Then sort, here i create another table tbl1
> tbl1 <- tbl[order( Value),]


You will get a ascending order 'Value'



If we want Decending order then the code will be,

> tbl1 <- tbl[order( -Value),]


Now  there is a need to sort the 'Value' Ascending when the SUB.ID is odd and descending when the SUB.ID is even.

To do this we need to new column, 'S_Value'
For SUB.IDs sub_4 and sub_4 change the 'Value' to negative

> tbl$S_Value <- ifelse((tbl$SUB.ID == 'sub_4' | tbl$SUB.ID == 'sub_6') , -tbl$Value, tbl$Value)


R Operators





Attach again
> attach(tbl)


Now sort by two columns

>  tbl3 <- tbl[order(SUB.ID, S_Value),]

We will get what we want..





































That's it.