Home > Blockchain >  How may I sort vectors for one vector by another vector?
How may I sort vectors for one vector by another vector?

Time:10-02

suppose I have two vectors; I want to sort x by y so that they are dependent:

> x
[1] 1 5 2
> y
[1] 4 5 1

I want the results of y is 1,5,4; so that the smallest value of y is in the first place because the smallest value of x is in first place.

Another example will be

> x
[1] 1 5 7 3 4 2
> y
[1] 4 5 6 2 6 8
> sort(y)[order(x)]
[1] 2 8 6 6 4 5

the above solution seems not work because the largest value in x is in the third place, but the largest value in sorted y is in the third place.

CodePudding user response:

foo = function(x, y){
    y[match(rank(x, ties.method = "first"), rank(y, ties.method = "first"))]
}
x <- c(1, 5, 2)
y <- c(4, 5, 1)
x1 <- c(1, 5, 7, 3, 4, 2)
y1 <- c(4, 5, 6, 2, 6, 8)
foo(x, y)
#[1] 1 5 4
foo(x1, y1)
#[1] 2 6 8 5 6 4

CodePudding user response:

We can use rank

sort(y)[rank(x)]
[1] 1 5 4
sort(y1)[rank(x1)]
[1] 2 6 8 5 6 4

Or do the order on the order

> sort(y)[order(order(x))]
[1] 1 5 4
> sort(y1)[order(order(x1))]
[1] 2 6 8 5 6 4

data

x <- c(1, 5, 2)
y <- c(4, 5, 1)
x1 <- c(1, 5, 7, 3, 4, 2)
y1 <- c(4, 5, 6, 2, 6, 8)
  • Related