-2

I have a data frame, which i want to reorder based on column mean. I want to reorder it by decreasing column mean

    SNR      SignalIntensity  ID
1   1.0035798        6.817374 109
2  11.9438978       11.545993 110
4   3.2894878        9.780420 112
5   4.0170266        9.871984 113
6   1.6310523        9.078186 114
7   1.6405415        8.228931 116
8   1.6625413        8.043536 117
9   0.8489116        6.179346 118
10  7.5312260       10.558180 119
11  7.2832911       10.474533 120
12  0.5732577        4.157294 121
14  0.8149754        6.045174 124

I use the following code

means <- colMeans(df)  ## to get mean
df <- df[,order(means)] ## to reorder 

to get the mean of columns and the order, but i get the column in increasing mean, opposite of my interest. what should i do to reorder in decreasing column mean

expected output

   ID SignalIntensity        SNR
1  109        6.817374  1.0035798
2  110       11.545993 11.9438978
4  112        9.780420  3.2894878
5  113        9.871984  4.0170266
6  114        9.078186  1.6310523
7  116        8.228931  1.6405415
8  117        8.043536  1.6625413
9  118        6.179346  0.8489116
10 119       10.558180  7.5312260
11 120       10.474533  7.2832911
12 121        4.157294  0.5732577
14 124        6.045174  0.8149754
Joshua
  • 40,822
  • 8
  • 72
  • 132
Agaz Wani
  • 5,514
  • 8
  • 42
  • 62
  • 2
    I would suggest to take a look at [this](http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r). The first Google hit on pretty much any "sort"/"order" and "r" variation. – David Arenburg Apr 12 '15 at 11:50

1 Answers1

1

The default settings in order is decreasing=FALSE. We can change that to TRUE

df[order(means, decreasing=TRUE)]

Or get the order of negative values of 'means'

df[order(-means)]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @AaghazHussain No problem. You can check more details in `?order` – akrun Apr 12 '15 at 11:45
  • 1
    BTW, with the devel version of `data.table` you can now order data frames *by reference* without converting to a data table. Using something like `setcolorder(df, order(-means))` – David Arenburg Apr 12 '15 at 13:09