Colonel Beauvel
Colonel Beauvel

Reputation: 31161

R find order of a vector

I have these two vectors:

x=c('a','c','b','b','c','a','d','d')
y=c(1, 4, 2, 4, 5, 9, 3, 3)

I want the order of x based on value of y such that each group in x are ordered following their minimum in y. Moreover within each group a, b, c, d, I want the order depending on ascending values of y.

eg the result of this ordering per group is:

x |a a b b d d c c
y |1 9 2 4 3 3 4 5

Hence the output must be:

output = c(1, 7, 3, 4, 8, 2, 5, 6)

I tried to use ave but can't combine both:

> ave(y, x, FUN=function(u) rank(u, ties.method='first'))
[1] 1 1 1 2 2 2 1 2
> ave(y, x, FUN=min)
[1] 1 4 2 2 4 1 3 3

Upvotes: 3

Views: 2205

Answers (1)

josliber
josliber

Reputation: 44309

You are trying to order first by the grouped y minimum and then by the y value itself, so you should pass these as the first and second arguments to the order function:

ordering <- order(ave(y, x, FUN=min), y)
x[ordering]
# [1] "a" "a" "b" "b" "d" "d" "c" "c"
y[ordering]
# [1] 1 9 2 4 3 3 4 5

Upvotes: 2

Related Questions