【问题标题】:Rcpp: rearrange a vector in an order of another vectorRcpp:按照另一个向量的顺序重新排列一个向量
【发布时间】:2018-01-05 17:13:41
【问题描述】:

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

A=c(0.5,0.4,0.2,0.9)
B=c(9,1,3,5)

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

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

我找到了如何使用sort_index 查找B 的顺序,但是我没有针对B 的顺序排列A

我该怎么做?

【问题讨论】:

标签: c++ r sorting rcpp


【解决方案1】:

您应该可以为此使用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)
*/

结果:

> arma_sort(A, B)
     [,1]
[1,]  0.4
[2,]  0.2
[3,]  0.9
[4,]  0.5

当然,还有其他方法。在普通 C++ 的上下文中,在 Stack Overflow 上已经多次询问过这个问题的变体。下面我将答案 here 改编为 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)
*/

结果:

> Rcpp_sort(A, B)
[1] 0.4 0.2 0.9 0.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多