R: reorder rank-based data columns

I have the 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 to reorder this data frame so that it is in descending order based on the "Total" line.

The resulting data file should look like this (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

Note that the columns that were previously ordered as β€œCA, AR, OR” now become β€œOR, CA, AR” based on a common row (sorted in descending order.)

To do this, I tried using the rank function as follows:

rank_total <- rank(-df1)

This gives me the title:

 [1] 2 1 3

However, I do not know how to reorder now based on these ranks.

Does anyone know how to proceed here? Or, if there is another way to do this, it will be great!

Thank you very much!

+4
source
1

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

rank

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

 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))
+3

All Articles