user4918087
user4918087

Reputation: 421

R: rearrange columns of dataframe, based on rank

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 dataframe such that it is in descending order, based on "Total" row.

The resulting dataframe 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

Notice that the columns that were ordered before as "CA, AR, OR" have now become "OR, CA, AR" based on the total row (ordered in descending order.)

In order to do this, I attempted to use the rank function as follows:

rank_total <- rank(-df1)

This gives me the ranks:

 [1] 2 1 3

However, I don't know how to now reorder, based on these ranks.

Does anyone know how to continue from here? Or if there is another way to do this altogether, that would be great!

Thanks so much in advance!!

Upvotes: 4

Views: 634

Answers (1)

akrun
akrun

Reputation: 887128

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

Upvotes: 3

Related Questions