R: rearrange columns of dataframe, based on rank -


i have following dataframe (df1)

type     ca     ar       or alpha    2      3        5 beta     1      5        6 gamma    6      2        8 delta    8      1        9 total    17     11       28 

i want reorder dataframe such in descending order, based on "total" row.

the resulting dataframe should (df2)

    type     or    ca     ar            alpha     5    2      3             beta      6    1      5             gamma     8    6      2             delta     9    8      1             total     28   17     11 

notice columns ordered before "ca, ar, or" have become "or, ca, ar" based on total row (ordered in descending order.)

in order this, attempted use rank function follows:

rank_total <- rank(-df1) 

this gives me ranks:

 [1] 2 1 3 

however, don't know how reorder, based on these ranks.

does know how continue here? or if there way altogether, great!

thanks in advance!!

try

 df2 <- df1[,c(1, order(-unlist(df1[df1$type=='total',-1]))+1)]  df2  #   type or ca ar  #1 alpha  5  2  3  #2  beta  6  1  5  #3 gamma  8  6  2  #4 delta  9  8  1  #5 total 28 17 11 

or using rank

 df1[,c(1, match(1:3, rank(-unlist(df1[nrow(df1),-1])))+1)] 

data

 df1 <- structure(list(type = c("alpha", "beta", "gamma", "delta", "total"  ), ca = c(2l, 1l, 6l, 8l, 17l), ar = c(3l, 5l, 2l, 1l, 11l),    or = c(5l, 6l, 8l, 9l, 28l)), .names = c("type", "ca", "ar",   "or"), class = "data.frame", row.names = c(na, -5l)) 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -