Sort one vector based on another

I have 2 vectors,

x <- c (1,4,6,7,9,2)
y <- c (2,6,5,1,8,9)

I want to sort x and y both. y depends on x. As a result i want

x = (1,2,4,6,7,9)
y = (2,9,6,5,1,8)

I know that I can get the sort index x as

sort(x, index.return=TRUE)$ix

How to sort the vector y?

+4
source share
2 answers

We can use this as an index.

i1 <- sort(x, index.return=TRUE)$ix

Or with order

i1 <- order(x)
x[i1]
#[1] 1 2 4 6 7 9

y[i1]
#[1] 2 9 6 5 1 8
+2
source

you are looking for order(). It generates an index based on the values ​​in the vector. Using this index, you can sort your yvector

y[order(x)]
# [1] 2 9 6 5 1 8

Make sure the vectors are the same length. Otherwise, it NAwill be generated

x <- c (1,4,6,7,9,2,3)
y <- c (2,6,5,1,8,9)
y[order(x)]
# [1]  2  9 NA  6  5  1  8

or some values ​​will be lost

x <- c (1,4,6,7,9,2)
y <- c (2,6,5,1,8,9,3)
y[order(x)]
# [1] 2 9 6 5 1 8
+3
source

Source: https://habr.com/ru/post/1674552/


All Articles