Home > Blockchain >  Rank ordering a rows of a data.frame in R
Rank ordering a rows of a data.frame in R

Time:01-18

I was was if there is a way to rank-order rows of my Data below such that rows that simultaneously have the largest values on each of risk1, risk2 and risk3 (NOT TOTAL Of the three) are at the top?

For example, in my Desired_output, you see that id == 4 simultaneously has the largest values on risk1, risk2 and risk3 (4,3,2).

For all other ids, there is a 1 or 0 on at least one of the risk1, risk2 and risk3.

Note: Tie's are fine. 4,3,2 == 2,3,4 == 3,2,4.

Data = data.frame(id=1:4,risk1 = c(1,3,5,4), risk2 = c(8,2,1,3), risk3 = c(0,1,4,2))

Desired_output = read.table(h=T,text="
id  risk1 risk2 risk3
4     4     3     2
3     5     1     4
2     3     2     1
1     1     8     0
")

CodePudding user response:

Maybe this helps - loop over the rows, sort the elements, paste, convert to numeric, use that to order the rows

Data[order(-apply(Data[-1], 1, \(x) 
     as.numeric(paste(sort(x), collapse = "")))),]

-output

   id risk1 risk2 risk3
4  4     4     3     2
3  3     5     1     4
2  2     3     2     1
1  1     1     8     0

CodePudding user response:

This does the trick:

library(dplyr)

Data %>% 
  arrange(-row_number())
  id risk1 risk2 risk3
1  4     4     3     2
2  3     5     1     4
3  2     3     2     1
4  1     1     8     0
  • Related