R阶向量,使得大多数元素之间的差异为正

问题描述 投票:1回答:1

我有两个向量

A = c(30709,28587,21672,20873,19877)
B = c(20213,21865,26217,30558,31674)

向量B总是按升序排列

我需要对向量A进行混洗,使得当取差(A-B)时,大多数都应产生+ ve的结果。

在这里,输出A必须看起来像(20873,28587,30709,19877,21672),因为此顺序将给我3个差(A-B),即+ ve

r sorting vector difference
1个回答
0
投票

如果向量A和B具有许多元素,则此解决方案的计算量很大,但是在这种情况下,它是瞬时的。

perms <- as.data.frame(gtools::permutations(length(A), length(A), A))
perms$num_positives <- 0

for (i in 1:nrow(perms))
  perms$num_positives[i] <- sum(perms[i,] > B)

perms[order(perms$num_positives, decreasing = TRUE), ]

输出

       V1    V2    V3    V4    V5 num_positives
28  20873 19877 28587 30709 21672             3
34  20873 21672 28587 30709 19877             3
38  20873 28587 19877 30709 21672             3
40  20873 28587 21672 30709 19877             3
41  20873 28587 30709 19877 21672             3
...

num_positives是A和B之间的正差数。

在您的提示中,A的许多排列得到的正数A-B等于3,如输出所示。

© www.soinside.com 2019 - 2024. All rights reserved.