# Re: [R] sort question in a dataset?

From: zhijie zhang <epistat_at_gmail.com>
Date: Sun 15 Oct 2006 - 05:01:33 GMT

*Richard M. Heiberger* ,
You have showed a detailed informaton on order, but it seems that there's a little difference between my task and your suggestions. I'd like to give a clear example to show my task:

```x <-  c(2, 9, 18, 3, 2)
y <-  c(2,9,8,9,8)
z <-  c(21,5,5,19,7)
a <-  cbind(x, y, z)  #dataset
a
x y  z
[1,]  2 2 21
[2,]  9 9  5
[3,] 18 8  5
```

[4,] 3 9 19
[5,] 2 8 7
aa <- a[order(a[,"y"], decreasing=TRUE),] aaa <- aa[order(aa[,"x"], decreasing=FALSE),] aaa

x y z

```[1,]  2 8  7
[2,]  2 2 21
[3,]  3 9 19
[4,]  9 9  5
[5,] 18 8  5
```

But i hope to get the following results:

x y z

```[1,]  3 9 19
[2,]  9 9  5
[3,]  2 8  7
[4,] 18 8  5
[5,]  2 2 21
```

*That's to say to sort the dataset with decreasing y and ascending x simultaneously*.
BTW, what's the main difference between order() and sort()? I can't find some simple introduction on their differnce. Thanks very much!

On 10/15/06, Richard M. Heiberger <rmh@temple.edu> wrote:
>
> > ?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), ]
>
> ## Suppose we wanted descending order on y. A simple solution is
> rbind(x,y,z)[, order(x, -y, z)]
>

```--
With Kind Regards,

oooO:::::::::
(..):::::::::
:\.(:::Oooo::
::\_)::(..)::
:::::::)./:::
::::::(_/::::
:::::::::::::
[***********************************************************************]
Zhi Jie,Zhang ,PHD
Tel:86-21-54237149   epistat@gmail.com
Dept. of Epidemiology,school of public health,Fudan University
Postcode:200032
[***********************************************************************]
oooO:::::::::
(..):::::::::
:\.(:::Oooo::
::\_)::(..)::
:::::::)./:::
::::::(_/::::
:::::::::::::

[[alternative HTML version deleted]]

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help