Search code examples
rdataframesortingtablesorter

How to order rows in data frame for maximun net values in some columns in r


I have this dataframe

a <- c("5", 7, 9, "11")
b <- c("-8", "-10", -3, -1)
c <- c(-4, -1, "-6", "3")
df <- data.frame(a,b,c)
    a        b       c
1   5       -8      -4
2   7       -10     -1
3   9       -3      -6
4   11      -1       3

then I want the rows be ordered for the maximum net value in them, independently of the columns. I mean, I expect something like this:

    a        b       c
4   11      -1       3
2   7       -10     -1
3   9       -3      -6
1   5       -8      -4



as you can see it was sorted because the first row has the value of 11, the second (-10), the third (9), the fourth (-8).


Solution

  • You can get rowwise maximum of absolute values and order it.

    df[order(-do.call(pmax, abs(df))), ]
    
    #   a   b  c
    #4 11  -1  3
    #2  7 -10 -1
    #3  9  -3 -6
    #1  5  -8 -4