[R] sort file names in numerical order
Michael Hannon
jm_hannon at yahoo.com
Sat Jul 17 22:47:20 CEST 2010
> I get some file names by list.files().
> These names are in alphabetical order.
> I want to change it to logical numeric order.
> Example:
> > fileNames <- c("A10", "A1", "A2", "B1", "B2", "B10")
> > sort(fileNames)
> [1] "A1" "A10" "A2" "B1" "B10" "B2"
> I want to have:
> "A1" "A2" "A10" "B1" "B2" "B10"
>
> Is this possible?
Greetings. I see that you've gotten an elegant solution to your problem.
I've appended a poor-man's solution, which I generated more for my own
edification than for yours.
-- Mike
## modified file names, changed to exhibit sorting on letters
fileNames <- c("A10", "B10", "A1", "A2", "B1", "B2"); fileNames
## use regular expressions to pick off letters, numbers
fnLet <- gsub("(^[^0-9]+).*$", "\\1", fileNames); fnLet
fnNum <- gsub("^[^0-9]+(.*)$", "\\1", fileNames); fnNum
## need to force numeric sorting of the numbers
fnNum <- as.numeric(fnNum)
## find the order of the numbers, for later use in subsetting
fnNumOrd <- order(fnNum); fnNumOrd
## pack all the relevant information into a data frame, then select from that
fnPieces <- data.frame(fnLet, fnNum, fileNames, stringsAsFactors=FALSE);
fnPieces
## partial sort by numbers only (gives new df)
dfPartialSort <- fnPieces[fnNumOrd, ]; dfPartialSort
## find the order of the names, then select from new df with that
fnLetOrd <- order(dfPartialSort[, 1]); fnLetOrd
dfFullSort <- dfPartialSort[fnLetOrd, ]; dfFullSort
## the file names have "gone along for the ride", so pick them off now
sortedFileNames <- dfFullSort$fileNames; sortedFileNames
More information about the R-help
mailing list