[R] Reorder in decreasing order

Duncan Murdoch murdoch.duncan at gmail.com
Sun Jul 22 22:56:32 CEST 2012


On 12-07-22 12:27 PM, Sverre Stausland wrote:
> reorder() is probably the best way to order the levels in a vector
> without manually specifying the order. But reorder() orders by default
> in an increasing order: "The levels are ordered such that the values
> returned by ‘FUN’ are in increasing order."
>
> Is there a way to do what reorder() does, but order the levels
> according to a _decreasing_ order of the values?

Yes, as Weidong suggested:

 > x <- rnorm(20)
 > y <- factor(sample(letters[1:3], 20, replace=TRUE))
 > reorder(y, x, mean)
  [1] a a c c c b b a b a c c b b a a a a c a
attr(,"scores")
          a          b          c
-0.2012975  0.6117830  0.2180352
Levels: a c b
 >
 > reorder(y, x, function(x) -mean(x))
  [1] a a c c c b b a b a c c b b a a a a c a
attr(,"scores")
          a          b          c
  0.2012975 -0.6117830 -0.2180352
Levels: b c a

Duncan Murdoch



More information about the R-help mailing list