How to sort a dataframe by column(s) in R?

Answer

You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:

R> dd[with(dd, order(-z, b)),]
    b x y z
4 Low C 922 Med D 311  Hi A 813  Hi A 91

Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:

R> dd[ order(-dd[,4], dd[,1]),]
    b x y z
4 Low C 922 Med D 311  Hi A 813  Hi A 91
R>

rather than using the name of the column (and with() for easier/more direct access).

All r Questions

Ask your interview questions on r

Write Your comment or Questions if you want the answers on r from r Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---