[R] How can I sort a character type vector?

Marc Schwartz marc_schwartz at me.com
Thu Mar 11 00:57:38 CET 2010


One other option is to use the mixedsort() function, which is in the gtools package on CRAN:

library(gtools)

x <- c(4, 5, 6, 8, 9, 11, "Y", 1, 13, 15, 16, 20, 
       "X", 2, 3, 10, 14, 19, "XY", 7, 12, 18, 
       17, 22, 21)

> mixedsort(x)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13"
[14] "14" "15" "16" "17" "18" "19" "20" "21" "22" "X"  "XY" "Y" 

HTH,

Marc Schwartz



On Mar 10, 2010, at 5:36 PM, Phil Spector wrote:

> Soyeon -
>   It sounds like you want a combination of a numerical
> sort and a lexigraphical sort.  I think they need to be done separately, and then joined back together:
> 
>> myvec = scan(,what='')
> 1: 4  5  6  8  9  11 Y  1  13 15 16 20 X  2  3  10 14 19 XY 7  12 18 17 22 21
> 26: Read 25 items
>> myvecn = as.numeric(myvec)
> Warning message:
> NAs introduced by coercion 
>> c(sort(myvecn),sort(myvec[is.na(myvecn)]))
> [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"
> [16] "16" "17" "18" "19" "20" "21" "22" "X"  "XY" "Y"
> 
> 
> 
> On Wed, 10 Mar 2010, Soyeon Kim wrote:
> 
>> Dear All,
>> 
>> I want to sort a character type vector.
>> the vector is
>> [1] 4  5  6  8  9  11 Y  1  13 15 16 20 X  2  3  10 14 19 XY 7  12 18 17 22
>> [25] 21
>> 
>> and I want to sort  1-22 X Y XY or 1-22 X XY Y.
>> How can I do that?
>> 
>> Thanks,



More information about the R-help mailing list