[R] Sorting

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Sep 14 13:57:23 CEST 2009


On Sun, 2009-09-13 at 14:46 +0200, Erich Neuwirth wrote:
> months<-c("jan","feb","mar","apr","may","jun",
> 	"jul","aug","sep","oct","nov","dec")
> 	
> sortorder<-order(as.numeric(date2[,2]),match(date2[,1],months))

To save some key strokes, the above can be done via:

sortorder <- order(as.numeric(date2[,2]), 
                   match(date2[,1], tolower(month.abb))

making use of the constant 'month.abb'.

G

> 
> date2[sortorder,]
> 
> is probably what you want.
> 
> megh wrote:
> > I have following object :
> > 
> >> date2
> >        [,1]  [,2]  
> >   [1,] "apr" "1992"
> >   [2,] "aug" "1992"
> >   [3,] "dec" "1992"
> >   [4,] "feb" "1992"
> >   [5,] "jan" "1992"
> >   [6,] "jul" "1992"
> >   [7,] "jun" "1992"
> >   [8,] "mar" "1992"
> >   [9,] "may" "1992"
> >  [10,] "nov" "1992"
> >  [11,] "oct" "1992"
> >  [12,] "sep" "1992"
> >  [13,] "apr" "1993"
> >  [14,] "aug" "1993"
> >  [15,] "dec" "1993"
> >  [16,] "feb" "1993"
> >  [17,] "jan" "1993"
> >  [18,] "jul" "1993"
> >  [19,] "jun" "1993"
> >  [20,] "mar" "1993"
> >  [21,] "may" "1993"
> >  [22,] "nov" "1993"
> >  [23,] "oct" "1993"
> >  [24,] "sep" "1993"
> >  [25,] "apr" "1994"
> >  [26,] "aug" "1994"
> >  [27,] "dec" "1994"
> >  [28,] "feb" "1994"
> >  [29,] "jan" "1994"
> >  [30,] "jul" "1994"
> > 
> > Now I want to sort the elements like below, and want to get the index
> > numbers of "date2" under following sorting scheme.
> > 
> > "jan" "1992"
> > "feb" "1992"
> > "mar" "1992"
> > ............
> > "dec" "1992"
> > "jan" "1993"
> > "feb" "1993"
> > "mar" "1993"
> > ............
> > "dec" "1993"
> > "jan" "1994"
> > "feb" "1994"
> > "mar" "1994"
> > ............
> > "dec" "1994"
> > 
> > Can anyone help me please?
> 
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list