I would like to sort/arrange data by group. That's easy enough. However, I only want to sort values within specific groups, not all groups.
I found one possible instance of a similar question at the link. But I found it to be confusing due to the framing of the question by the OP. Arrange values within a specific group
Sample data:
df <- data.frame(var = c("apple", "banana", "eggplant", "carrot", "dill", "fava", "garlic"),
grp = c("A", "A", "B", "B", "B", "C", "C"),
val = c(4, 2, 1, 3, 7, 6, 2))
df
# var grp val
# 1 apple A 4
# 2 banana A 2
# 3 carrot B 3
# 4 dill B 7
# 5 eggplant B 1
# 6 fava C 6
# 7 garlic C 2
Desired output:
# var grp val
# 1 apple A 4
# 2 banana A 2
# 3 eggplant B 1
# 4 carrot B 3
# 5 dill B 7
# 6 garlic C 2
# 7 fava C 6
Partial solution:
library(dplyr)
df %>%
group_by(grp) %>%
arrange(val, .by_group = T)
This of course sorts for all groups. How do I get it to sort for only the groups I would like sorted, which are "B" and "C"? I would like a tidyverse solution but feel free to post a base solution as well.