Re: [R] sort question in a dataset?

From: Richard M. Heiberger <rmh_at_temple.edu>
Date: Sun 15 Oct 2006 - 04:02:17 GMT


> ?order
> x <- c(2, 9, 18, 3, 2)
> y <- c(2,5.6,5,9,8)
> z <- c(21,5,5,19,7)
> a <- cbind(x, y, z)
> a

      x y z

[1,]  2 2.0 21
[2,]  9 5.6  5
[3,] 18 5.0  5
[4,]  3 9.0 19
[5,]  2 8.0  7

> aa <- a[order(a[,"y"], decreasing=TRUE),]
> aaa <- aa[order(aa[,"x"], decreasing=FALSE),]
> aaa

      x y z

[1,]  2 8.0  7
[2,]  2 2.0 21
[3,]  3 9.0 19
[4,]  9 5.6  5
[5,] 18 5.0  5

>

a$y doesn't work because $ subscripting requires a data.frame. cbind creates an ordinary matrix. This works with a data.frame.
> a <- data.frame(x, y, z)
> aa <- a[order(a$y, decreasing=TRUE),]
> aaa <- aa[order(aa$x, decreasing=FALSE),]

Please use spaces for legibility on both sides of the assignment arrow and after a comma.

If you want all columns ascending (or descending), then you could do it in one step
> aaaa <- a[order(a$x, a$y), ]

See also the example in ?order
## Suppose we wanted descending order on y. A simple solution is rbind(x,y,z)[, order(x, -y, z)]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun Oct 15 14:23:10 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 15 Oct 2006 - 05:30:10 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.