I have a data frame that I want to sort by one column than the next, (using tidyverse if possible).
I checked the below address but the solutions did not seem to work.
Order a "mixed" vector (numbers with letters)
Sample code for an example:
variable <- c("channel", "channel", "channel", "comp_ded", "comp_ded", "comp_ded")
level <- c("DIR", "EA", "IA", "500", "750", "1000")
df <- as_tibble(cbind(variable, level))
This does not give me what I want:
df <- df %>% arrange(variable, level)
The order of the level columns are as follows:
variable level
channel DIR
channel EA
channel IA
level 1000
level 500
level 750
I need them:
variable level
channel DIR
channel EA
channel IA
level 500
level 750
level 1000
There are multiple different "variables" in the real data set where half need to be sorted in number order and half in alphabetical. Does anyone know how to do this?
The simplest solution would be to use dplyr::group_by
.
library(dplyr)
variable <- c("channel", "channel", "channel", "comp_ded", "comp_ded", "comp_ded")
level <- c("DIR", "EA", "IA", "500", "750", "1000")
df <- as_tibble(cbind(variable, level))
df %>%
group_by(variable, level) %>%
arrange()
# A tibble: 6 x 2
variable level
<chr> <fctr>
1 comp_ded DIR
2 comp_ded EA
3 comp_ded IA
4 channel 500
5 channel 750
6 channel 1000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With