简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM