Rcpp:按另一个向量的顺序重新排列一个向量

1 c++ sorting r rcpp

我是 Rcpp 的新手。我需要A按照另一个向量的顺序重新排列一个向量B;例如,

A=c(0.5,0.4,0.2,0.9)
B=c(9,1,3,5)
Run Code Online (Sandbox Code Playgroud)

我想C=c(0.4,0.2,0.9,0.5)通过 Rcpp 制作。

我知道简单的 r 代码,C=A[order(B)]但是我有必要使用 Rcpp 代码。

我找到了如何B通过 using找到 的顺序sort_index,但我未能A就 的顺序进行安排B

我怎样才能做到?

duc*_*ayr 6

您应该可以使用arma::sort_index它,您在帖子中提到了这一点:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec arma_sort(arma::vec x, arma::vec y) {
    return x(arma::sort_index(y));
}

/*** R
A <- c(0.5, 0.4, 0.2, 0.9)
B <- c(9, 1, 3, 5)
arma_sort(A, B)
*/
Run Code Online (Sandbox Code Playgroud)

结果:

> arma_sort(A, B)
     [,1]
[1,]  0.4
[2,]  0.2
[3,]  0.9
[4,]  0.5
Run Code Online (Sandbox Code Playgroud)

当然,还有其他方式。在纯 C++ 的上下文中,已在 Stack Overflow 上多次询问有关此问题的变体。下面我为 Rcpp修改了这里的答案:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector Rcpp_sort(NumericVector x, NumericVector y) {
    // Order the elements of x by sorting y
    // First create a vector of indices
    IntegerVector idx = seq_along(x) - 1;
    // Then sort that vector by the values of y
    std::sort(idx.begin(), idx.end(), [&](int i, int j){return y[i] < y[j];});
    // And return x in that order
    return x[idx];
}

/*** R
A <- c(0.5, 0.4, 0.2, 0.9)
B <- c(9, 1, 3, 5)
Rcpp_sort(A, B)
*/
Run Code Online (Sandbox Code Playgroud)

结果:

> Rcpp_sort(A, B)
[1] 0.4 0.2 0.9 0.5
Run Code Online (Sandbox Code Playgroud)