2

Hi I have a list of files:

    "1_EX-P1-H2.3000"    "10_EX-P1-H2.3002"   "100_EX-P1-H2.3074" 
    "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070" "2_EX-P1-H2.3000" "3_EX-P1-H2.3000" "4_EX-P1-H2.3000" 
    "5_EX-P1-H2.3001"

I want to sort not by lexicographically order but buy the order of the first number before the "_", these numbers go from 1 to 1000. So as result I should obtain:

    "1_EX-P1-H2.3000"    "2_EX-P1-H2.3000" "3_EX-P1-H2.3000" "4_EX-P1-H2.3000" 
    "5_EX-P1-H2.3001"    "10_EX-P1-H2.3002"   "100_EX-P1-H2.3074" 
    "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070" 
Will
  • 1,619
  • 5
  • 23
  • 2
    This seems like the same as [your last question](https://stackoverflow.com/q/65131628/903061), and the same solution works - notice Akrun's solution is the same as the [top answer to the duplicate of your old question](https://stackoverflow.com/a/2778060/903061) – Gregor Thomas Dec 03 '20 at 20:21

1 Answers1

0

As the OP mentioned to order based on the first number before the _, we can use parse_number from readr to extract the first numeric substring, order and use that to rearrange the vector

v1[order(readr::parse_number(v1))]
#[1] "1_EX-P1-H2.3000"    "2_EX-P1-H2.3000"    "3_EX-P1-H2.3000"    "4_EX-P1-H2.3000"    "5_EX-P1-H2.3001"    "10_EX-P1-H2.3002"  
#[7] "100_EX-P1-H2.3074"  "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070"

Or using sub to remove the substring, order

v1[order(as.numeric(sub("_.*", "", v1)))]
#[1] "1_EX-P1-H2.3000"    "2_EX-P1-H2.3000"    "3_EX-P1-H2.3000"    "4_EX-P1-H2.3000"    "5_EX-P1-H2.3001"    "10_EX-P1-H2.3002"  
#[7] "100_EX-P1-H2.3074"  "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070"

Or another option is mixedsort from gtools

gtools::mixedsort(v1)

-output

#[1] "1_EX-P1-H2.3000"    "2_EX-P1-H2.3000"    "3_EX-P1-H2.3000"    "4_EX-P1-H2.3000"    "5_EX-P1-H2.3001"    "10_EX-P1-H2.3002"  
#[7] "100_EX-P1-H2.3074"  "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070"

data

v1 <- c("1_EX-P1-H2.3000", "10_EX-P1-H2.3002", "100_EX-P1-H2.3074", 
"1004_EX-P1-H2.4059", "1006_EX-P1-H2.4070", "2_EX-P1-H2.3000", 
"3_EX-P1-H2.3000", "4_EX-P1-H2.3000", "5_EX-P1-H2.3001")
akrun
  • 874,273
  • 37
  • 540
  • 662