Rock
Rock

Reputation: 2967

Sort one column while keeping the other one fixed (within the other)

With

df <- data.frame(x = rep(1:3, each = 3)
        , y = rep(1:3, 3)
        , z = round(rnorm(9), 2))

df
  x y     z
1 1 1  0.55
2 1 2  0.99
3 1 3 -2.32
4 2 1 -0.25
5 2 2  1.20
6 2 3 -0.38
7 3 1  1.07
8 3 2 -0.98
9 3 3 -1.09

Is there a way to sort z within each x so that:

df.sort
  x y     z
1 1 3 -2.32
2 1 1  0.55
3 1 2  0.99
4 2 3 -0.38
5 2 1 -0.25
6 2 2  1.20
7 3 3 -1.09
8 3 2 -0.98
9 3 1  1.07

Thanks!

Upvotes: 0

Views: 301

Answers (2)

mnel
mnel

Reputation: 115382

If you want to sort by z within each value of x ( what your example shows, not really what your question seems to lead towards, you can use plyr and arrange

library(plyr)
dfa <- arrange(df, x, z)

What you are doing here is ordering first by x, then by z

Upvotes: 1

johannes
johannes

Reputation: 14413

You could create a new data.frame on the fly.

data.frame(df$x, df[order(df$z), c("y", "z")])

Upvotes: 1

Related Questions