Rank columns and put the column with the highest score as first and so on

dataframe, r

Solution

How about this?

> testfr[rev(order(sapply(testfr, max, na.rm = TRUE)))]

Break down:

sapply(test.fr, max, na.rm = TRUE) # get max of each column (after removing NA)
order(.) # get the order of these values in increasing order
rev(.)   # get the reverse order so that highest value index stays first
testfr[.] # get the columns in this order back

Problem

Lets say i have a very large data.frame containing scores per column. for example: ``` MA0001.1 AGL3 MA0003.1 TFAP2A MA0004.1 Arnt MA0005.1 AG MA0006.1 Arnt::Ahr 7.789524e-09 0.4012127249 3.771518e-03 1.892011e-06 0.002733200 5.032498e-07 0.0001873801 9.947449e-05 3.284222e-05 0.001367041 1.194487e-06 0.0009357406 6.943634e-05 1.589373e-05 0.002551519 4.833494e-06 0.0150703600 1.003488e-04 1.197928e-03 0.001431416 6.865040e-05 0.0000732607 3.857193e-04 5.388744e-03 0.001363706 ``` R data.frame: ``` testfr<-structure(list(`MA0001.1 AGL3` = c(7.78952366977488e-09, 5.03249791215203e-07, 1.19448739380034e-06, 4.83349413748598e-06, 6.86504034402563e-05 ), `MA0003.1 TFAP2A` = c(0.401212724871542, 0.000187380067026448, 0.000935740631438077, 0.0150703600158589, 7.32607018758816e-05 ), `MA0004.1 Arnt` = c(0.00377151826447817, 9.94744903768433e-05, 6.94363387424972e-05, 0.000100348764966112, 0.00038571926458373 ), `MA0005.1 AG` = c(1.89201084302835e-06, 3.2842217133538e-05, 1.58937284554136e-05, 0.00119792816070882, 0.00538874414923338 ), `MA0006.1 Arnt::Ahr` = c(0.00273319966783363, 0.00136704060025893, 0.00255151921946167, 0.00143141576426544, 0.00136370552325235 )), .Names = c("MA0001.1 AGL3", "MA0003.1 TFAP2A", "MA0004.1 Arnt", "MA0005.1 AG", "MA0006.1 Arnt::Ahr"), class = "data.frame", row.names = c(4L, 2L, 5L, 1L, 3L)) ``` Now i want to select the column with the highest values in it and place that column first. So the values of 1 column should stay below the same column name and the entire column should move by rank. I tried the following: ``` ranked<-unlist(lapply(testfr,rank)) testranked<-testfr[ranked, ] ``` this produces a data frame with 2259obs*459vars while the original was 5*459. Note that, testfr is a data.frame derived from a function which scores sequences on to a list of matrices! And gives that score back into a data.frame where the rows are the sequences and the columns are the matrices. I know i do something wrong with the indexing or unlisting but i dont have any clue how to fix this. Any help is appreciated.

Original source