I would like to re-arrange my data according to a score variable value
and an additional group
variable. However, depending on the group
the sorting should either be descending or ascending. The groups are consisting of test scores (higher is better) and processing time (lower is better).
df <- data.frame(id = rep(1:4, 4),
value = rnorm(16, 5),
group = c(paste0("test", 1:3), "time0"))
df$value[seq(4,16, 4)] <- 1:4
> df %>% group_by(group) %>% arrange(group, desc(value))
# A tibble: 16 x 3
# Groups: group [4]
id value group
<int> <dbl> <fct>
1 3 6.06 test1
2 4 4.69 test1
3 1 4.32 test1
4 2 3.56 test1
5 4 5.96 test2
6 1 5.96 test2
7 3 4.43 test2
8 2 3.86 test2
9 3 6.28 test3
10 4 5.55 test3
11 2 4.59 test3
12 1 3.53 test3
13 4 4 time0
14 3 3 time0
15 2 2 time0
16 1 1 time0
The desired output looks like this:
id value group
<int> <dbl> <fct>
1 3 6.06 test1
2 4 4.69 test1
3 1 4.32 test1
4 2 3.56 test1
5 4 5.96 test2
6 1 5.96 test2
7 3 4.43 test2
8 2 3.86 test2
9 3 6.28 test3
10 4 5.55 test3
11 2 4.59 test3
12 1 3.53 test3
13 4 1 time0
14 3 2 time0
15 2 3 time0
16 1 4 time0
I tried using arrange_if
but could not figure it out.
Any help is much appreciated.
Thanks for the answers so far, they are equally helpful!
EDIT for Clarification: This is different from this question since the sorting is not only based on multiple columns but also dependend on within-column characteristics.