简体   繁体   English

在R中以锁步方式对两个向量进行排序的最有效方法是什么?

[英]Most efficient way to sort two vectors in lockstep in R?

What's the most efficient way to sort two vectors in lockstep in R? 在R中以锁步方式对两个向量进行排序的最有效方法是什么? The first vector should be sorted in ascending order and the second should be reordered in lockstep such that elements with corresponding indices before the sort still have corresponding indices after the sort. 第一个向量应按升序排序,第二个向量应以锁步方式重新排序,以使排序前具有相应索引的元素在排序后仍具有相应的索引。 For example: 例如:

foo <- c(1,3,2, 5,4)
bar <- c(2,6,4,10,8)
sort2(foo, bar)

# foo == c(1,2,3,4, 5)
# bar == c(2,4,6,8,10)

Note: Efficiency is an absolute must here as I am trying to use this as the basis for creating an O(N log N) implementation of Kendall's Tau to submit as a patch. 注意:效率是绝对必须的,因为我试图将此作为创建Kendall的Tau的O(N log N)实现的基础,以作为补丁提交。 I'd like to avoid writing my own special function in C to do this, but would be willing to if it can't be done efficiently within R. 我想避免在C中编写我自己的特殊功能来做这件事,但是如果它不能在R内有效地完成,我愿意。

Not sure I understand but is this use of order() what you want: 不确定我理解但是这是使用order()你想要的:

R> foo <- c(1,3,2, 5,4)
R> bar <- c(2,6,4,10,8)
R> fooind <- order(foo)   # index of ordered 
R> foo[fooind]
[1] 1 2 3 4 5
R> bar[fooind]
[1]  2  4  6  8 10
R> 

I'm not sure that the accepted answer is correct in cases where X is sorted first, then Y is sorted by the index of (sorted) X, in that if there are duplicate values in X, Y does not always get sorted in classic 'order by x, y' style. 我不确定在X先排序的情况下接受的答案是否正确,然后Y按(排序)X的索引排序,因为如果X中有重复值,Y并不总是按经典排序'按x,y'排序。 For example: 例如:

> x <- c(3,2,2,2,1)
> y <- c(5,4,3,2,1)
> xind <- order(x)
> x[xind]
[1] 1 2 2 2 3
> y[xind]
[1] 1 4 3 2 5

Y is ordered by the new order of X, but not in lockstep, as not all of the X indexes changed. Y X的新的顺序排列,而不是步调一致,作为X指标不是一切都改变了。 A simple function to do as the OP required: 一个简单的功能,需要做OP:

> sort.xy <- function(x,y)
+ {
+ df.xy <- data.frame(x,y)
+ df.xy[ order(df.xy[,1], df.xy[,2]), ]
+ }

In use: 正在使用:

> c(sort.xy(x,y))
$x
[1] 1 2 2 2 3

$y
[1] 1 2 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM