2

I have data that looks like the following, except the numbers are out of order:

dat<-
paste("Experience",1:20,sep="_")

Basically, I am trying to sort the columns in numerical order based on the ending number to order them as the code above produces. However, when I sort the values, it sorts based on the first digit as such:

"Experience_1"  "Experience_10"  "Experience_11" "Experience_12" 
"Experience_13" "Experience_14"  "Experience_15" "Experience_16" 
"Experience_17" "Experience_18" "Experience_19" "Experience_2" 
"Experience_20" "Experience_3"  "Experience_4"  "Experience_5" 
"Experience_6"  "Experience_7" "Experience_8"  "Experience_9"

Thoughts?

costebk08
  • 1,299
  • 4
  • 17
  • 42
  • 1
    I dont quite understand. can you provide a minimal example of (i) how your dataframe currently looks like and (ii) what the intended dataframe should look like? – safex May 08 '19 at 15:02

2 Answers2

4

The Stringr library, a part of the tidyverse, has str_sort() which sorts strings numerically in R.

library(stringr)
str_sort(dat, numeric = TRUE)
M.Viking
  • 5,067
  • 4
  • 17
  • 33
3

An option would be mixedsort from gtools

gtools::mixedsort(dat)
#[1] "Experience_1"  "Experience_2"  "Experience_3"  "Experience_4"  "Experience_5"  "Experience_6" 
#[7] "Experience_7"  "Experience_8"  "Experience_9"  "Experience_10" "Experience_11" "Experience_12"
#[13] "Experience_13" "Experience_14" "Experience_15" "Experience_16" "Experience_17" "Experience_18"
#[19] "Experience_19" "Experience_20"
akrun
  • 874,273
  • 37
  • 540
  • 662