Paavo Pohndorff
Paavo Pohndorff

Reputation: 333

Sorting a character vector by numbers in parentheses

These chr have to be sorted:

files <- c("file (1).csv", "file (2).csv", "file.csv")

into:

chr [1:3] "file.csv" "file (1).csv" "file (2).csv"

So far I have found the gtools package with its mixedsort and mixedorder function. But they result in:

> library("gtools")
> mixedsort(files)    
[1] "file (1).csv" "file (2).csv" "file.csv"

Any idea to solve my problem?

Upvotes: 0

Views: 101

Answers (1)

akrun
akrun

Reputation: 887213

We can use sub

i1 <- as.numeric(gsub("\\D+", "", files))
files[order(!is.na(i1), i1)]
#[1] "file.csv"     "file (1).csv" "file (2).csv"

Upvotes: 4

Related Questions