It sounds like you would be interested in the mixedsort
function from "gtools".
Consider the following sample data:
set.seed(1)
x <- paste("Q", sample(5, 20, TRUE), sample(20, 20, TRUE), sep = "_")
x
# [1] "Q_2_19" "Q_2_5" "Q_3_14" "Q_5_3" "Q_2_6" "Q_5_8" "Q_5_1"
# [8] "Q_4_8" "Q_4_18" "Q_1_7" "Q_2_10" "Q_1_12" "Q_4_10" "Q_2_4"
# [15] "Q_4_17" "Q_3_14" "Q_4_16" "Q_5_3" "Q_2_15" "Q_4_9"
Here's the result of sort
:
sort(x)
# [1] "Q_1_12" "Q_1_7" "Q_2_10" "Q_2_15" "Q_2_19" "Q_2_4" "Q_2_5"
# [8] "Q_2_6" "Q_3_14" "Q_3_14" "Q_4_10" "Q_4_16" "Q_4_17" "Q_4_18"
# [15] "Q_4_8" "Q_4_9" "Q_5_1" "Q_5_3" "Q_5_3" "Q_5_8"
Here's the result of mixedsort
:
library(gtools)
mixedsort(x)
# [1] "Q_1_7" "Q_1_12" "Q_2_4" "Q_2_5" "Q_2_6" "Q_2_10" "Q_2_15"
# [8] "Q_2_19" "Q_3_14" "Q_3_14" "Q_4_8" "Q_4_9" "Q_4_10" "Q_4_16"
# [15] "Q_4_17" "Q_4_18" "Q_5_1" "Q_5_3" "Q_5_3" "Q_5_8"
I hope this is enough to be helpful for you--otherwise, please update your question with a reproducible example.