如何根据另一个向量的值对一个向量进行排序 [英] How do I sort one vector based on values of another
本文介绍了如何根据另一个向量的值对一个向量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量x,我想根据向量y中值的顺序进行排序.这两个向量的长度不同.
I have a vector x, that I would like to sort based on the order of values in vector y. The two vectors are not of the same length.
x <- c(2, 2, 3, 4, 1, 4, 4, 3, 3)
y <- c(4, 2, 1, 3)
预期结果将是:
[1] 4 4 4 2 2 1 3 3 3
推荐答案
这是一个班轮...
y[sort(order(y)[x])]
[edit:]分解如下:
[edit:] This breaks down as follows:
order(y) #We want to sort by y, so order() gives us the sorting order
order(y)[x] #looks up the sorting order for each x
sort(order(y)[x]) #sorts by that order
y[sort(order(y)[x])] #converts orders back to numbers from orders
这篇关于如何根据另一个向量的值对一个向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文