[R] sort question in a dataset?

Richard M. Heiberger rmh at temple.edu
Sun Oct 15 06:02:17 CEST 2006


> ?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)]



More information about the R-help mailing list