Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rank ordering a rows of a data.frame in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading