Home > Back-end >  How to order rows in data frame for maximun net values in some columns in r
How to order rows in data frame for maximun net values in some columns in r

Time:09-17

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)

CodePudding user response:

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

CodePudding user response:

This solutions works, but it is not the most elegant one

libray(dplyr)

df %>% 
  rowwise() %>% 
  mutate(max_row_value = max(abs(c_across(a:c)))) %>% 
  arrange(-max_row_value)

# A tibble: 4 x 4
# Rowwise: 
      a     b     c max_row_value
  <dbl> <dbl> <dbl>         <dbl>
1    11    -1     3            11
2     7   -10    -1            10
3     9    -3    -6             9
4     5    -8    -4             8
  • Related