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)]
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)]
source
share