Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ordering a vector of characters in R

Tags:

r

character

I'm trying to order a vector of states. I understand this should be very simple but I can't work it out. I have viewed other posts that suggests complicated solutions using vapply(...) but this seems unnecessary. I have the following:

  state.vec = c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "CD", "FL", "AG", "HI", "DI",   
  "IL", "IN", "AI", "KS", "KY", "AL", "EM", "DM", "AM", "IM", "MN", "MS", "MO", "MT", "EN", "NV",   
  "HN", "JN", "MN", "NY", "CN", "DN", "HO", "KO", "OR", "AP", "PR", "IR", "CS", "DS", "NT", "TX",  
  "TU", "TV", "IV", "AV", "AW","VW", "IW", "WY", "GU")

Unfortunately, order converts the values to their integer order:

 order(state.vec) 
 2  1  4  3  5  6  7  9  8 10 11 54 12 16 13 14 15 17 18 19 22 21 20 23 24 26 25 27 34 35 28   
 30 31 32 29 33 36 37 38 39 40 41 42 43 44 45 46 49 48 47 50 52 51 53

It's clever enough to recognize that 'AK' comes before 'AL' and hence 'AL' corresponds to second or the integer 2. Ideally, I would like it to re-order the vector so that it does go from 1:53 appropriately, e.g. ('AK', 'AL', 'AR', ... etc.

like image 492
hubert_farnsworth Avatar asked Dec 04 '22 12:12

hubert_farnsworth


1 Answers

state.vec[order(state.vec)]

or simply:

sort(state.vec)
like image 72
sebastian-c Avatar answered Dec 18 '22 17:12

sebastian-c