I am trying to use dplyr's arrange to sort character strings based on a condition. I'd like to arrange on a column, but in ascending order if a second column is equal to one value and in descending order if the second column is equal to another value.
I found a couple similar questions (one of them one of my own previous questions), but they weren't directly applicable. Both of them sorted on numeric columns and they wouldn't work on character columns.
R - Conditionally sort multiple columns as ascending or descending by group
Sort/arrange within group for only chosen groups
Here's sample data:
df <- mtcars %>% as_tibble(rownames = "model") %>% select(model, mpg, cyl) %>% slice(1:8) %>% mutate(cond = c(rep("A", 4), rep("B", 4)))
If cond == "A", I want to sort "model" in ascending order. If cond == "B", I want to sort "model" in descending order. I'd like a solution that doesn't rely on bind_rows or a similar solution.
Possibly something in the form of:
library(dplyr)
df %>% arrange(ifelse(cond == "A", model, desc(model)))
The desired solution looks like:
## A tibble: 8 x 8
# model mpg cyl cond
# <chr> <dbl> <dbl> <chr>
#1 Datsun 710 22.8 4 A
#2 Hornet 4 Drive 21.4 6 A
#3 Mazda RX4 21 6 A
#4 Mazda RX4 Wag 21 6 A
#5 Valiant 18.1 6 B
#6 Merc 240D 24.4 4 B
#7 Hornet Sportabout 18.7 8 B
#8 Duster 360 14.3 8 B