[R] sort file names in numerical order
Duncan Mackay
mackay at northnet.com.au
Sun Jul 18 11:16:05 CEST 2010
Hi
Yes it is possible- one way is:
fileNames[order(sprintf("%02s", sub("[[:upper:]]","", fileNames)))]
[1] "A1" "B1" "A2" "B2" "A10" "B10"
Regards
Duncan
Duncan Mackay
Department of Agronomy and Soil Science
University of New England
ARMIDALE NSW 2351
Email home: mackay at northnet.com.au
At 06:47 18/07/2010, you wrote:
> > 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
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list