[R] Custom Sort Character and Numeric
jim holtman
jholtman at gmail.com
Sun Oct 16 14:04:00 CEST 2011
Here is another solution that gets the order you posted:
> myArray <- c('AFP9','AFR9','TLQP7','AFS9','AFR8','AFP8','AFS7','TLQS8')
> # create a sort key
> key <- sub("^(.*)(.)(.)$", "\\3\\2\\1", myArray)
> key
[1] "9PAF" "9RAF" "7PTLQ" "9SAF" "8RAF" "8PAF" "7SAF" "8STLQ"
> # sort, but don't get your output
> myArray[order(key)]
[1] "TLQP7" "AFS7" "AFP8" "AFR8" "TLQS8" "AFP9" "AFR9" "AFS9"
> # to get your output, new key
> newKey <- sub("^(.*)(.)(.)$", "\\1\\3\\2", myArray)
> newKey
[1] "AF9P" "AF9R" "TLQ7P" "AF9S" "AF8R" "AF8P" "AF7S" "TLQ8S"
> myArray[order(newKey)]
[1] "AFS7" "AFP8" "AFR8" "AFP9" "AFR9" "AFS9" "TLQP7" "TLQS8"
>
On Sun, Oct 16, 2011 at 4:47 AM, swonder03 <ramey.steven at gmail.com> wrote:
> I"m trying to do a custom sort in this order:
>
> 1) Numeric digit furthest right;
> 2) Alphabetical second furthest to the right;
> 3) Alphabetical the rest of the string beginning with the first character;
>
> The example code I'm using is an array that follows:
>
> /myArray <- c('AFP9','AFR9','TLQP7','AFS9','AFR8','AFP8','AFS7','TLQS8')/
>
> The output I desire is:
>
> />myArray
> [1] "AFS7" "AFP8" "AFR8" "AFP9" "AFR9" "AFS9" "TLQP7" TLQS8" /
>
> What I'm thinking is writing a function that will order it by analyzing it
> from right to left. Ideally there would be a way to look at the individual
> strings like the formula in Excel "=RIGHT(cell, 1)" and drop the furthest
> right then do the same thing to the next character. I've been looking into
> custom sort for R and haven't found much. Any idea what this function would
> look like? Possibly a while loop? Each string would have a length of at
> least 3, possibly longer. Thank you in advance.
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Custom-Sort-Character-and-Numeric-tp3909058p3909058.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list