-4

I have a rather long dataframe with 200+ columns like this:

RespondentID  Q16_positiv.31    Q16_positiv.68  Q16_positiv.194 ....

Is there a way to sort the Q16_positiv.XYZ variables numerically ascending? All my attempts used aplhabetical sort, which does yield the expected results.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85

1 Answers1

2

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.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485