R - Sort dataframe with multiple columns


  • An example to show how to sort (including descending order) dataframe with multiple column values.
  •  > data  # if we have data.frame (variable data here)
       b x y z  
     1 Hi A 8 1  
     2 Med D 3 1  
     3 Hi A 9 1  
     4 Low C 9 2    
     > data[order(data[,4]),]  # sort by 4th column, which is z here
       b x y z  
     1 Hi A 8 1  
     2 Med D 3 1  
     3 Hi A 9 1  
     4 Low C 9 2  
     > data[order(-data[,4]),]  # sort by 4th column, with descending order 
       b x y z  
     4 Low C 9 2  
     1 Hi A 8 1  
     2 Med D 3 1  
     3 Hi A 9 1  
     > data[order(-data[,4], data[,3]),]  # sort by 4th column(z), then sort by 3rd column(y)
       b x y z  
     4 Low C 9 2  
     2 Med D 3 1  
     1 Hi A 8 1  
     3 Hi A 9 1  
    

No comments:

Post a Comment