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

Sort column based on another that has already been sorted

I have a dataframe df that looks like this:

ID Value
37 +6
23 +9
51 +13
37 -14
23 -17
51 -20

I need df$Value to be sorted so it’ll look like this:

ID Value
37 +6
37 -14
23 +9
23 -17
51 +13
51 -20

Because it’s important to keep the first column’s order.

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

Would anyone know how to help me? I thank you in advance.

>Solution :

First set ID as factor, then arrange on Value.

library(dplyr)

df %>% mutate(ID = factor(ID, levels = unique(ID))) %>% arrange(ID, desc(Value))

  ID Value
1 37     6
2 37   -14
3 23     9
4 23   -17
5 51    13
6 51   -20
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