[R] Sorting problem

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 24 13:26:25 CET 2004


On Fri, 24 Dec 2004 Ted.Harding at nessie.mcc.ac.uk wrote:

> On 24-Dec-04 Gabor Grothendieck wrote:
>>
>> From:   Paul JH Drake <p.drake at beatson.gla.ac.uk>
>>>
>>> When I plot data as a boxplot, the boxes appear on the plot in
>>> alphabetical order (of group) rather than the order in which they
>>> appear
>>> in the data. So far, the only thing I can do to fix this is to prefix
>>> the group labels with a,b,c...etc to trick R into plotting them in the
>>> right order.
>>>
>>> Can sorting be turned off?
>>> How should I address this sensibly?
>>
>> Actually they are shown in order of the levels of the factor.

That's making lots of unsubstantiated assumptions, including that the 
formula interface to boxplot() was used: we do not even know that 
boxplot() was used (rather than plot.factor or bwplot or ...).

>> e.g. to show them in reverse order:
>>
>> attach(InsectSprays)
>> spray <- factor( as.character(spray), level = rev(levels(spray)) )
>> boxplot(count ~ spray)
>
> Applying boxplot to data constructed as follows:
>
>  X<-list(C=rnorm(10),B=rnorm(20),A=rnorm(30))
>  boxplot(X)
>
> gives the plots in the order "C", "B", "A", so here they indeed
> come out in the order of the data.
>
> But suppose I had wanted them in the order "B", "A", "C", say.
> How would Gabor's suggestion (or similar) be applied to this case?
>
> (OK I'm being thick, maybe; but I can't see how to relate the
> one to the other!)

They are not related.  You need to reorder the elements in your list:

boxplot(X[c("B", "A", "C")])

The help page for boxplot in R-devel explains both approaches.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list