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.
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