Rcpp:按另一个向量的顺序重新排列向量 [英] Rcpp: rearrange a vector in an order of another vector

查看:160
本文介绍了Rcpp:按另一个向量的顺序重新排列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in Rcpp. I need to rearrange a vector A in an order of another vector B; For example,

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代码.

I know the simple r code, C=A[order(B)], but it is necessary for me to use Rcpp code.

我发现了如何使用sort_index查找B的顺序,但是我没有按照B的顺序排列A.

I found how to find the order of B by using sort_index, but I fail to arrange A with respect to an order of B.

我该怎么做?

推荐答案

为此,您应该可以使用arma::sort_index来实现,

You should be able to use arma::sort_index for this, which you mention in your post:

#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上对这个问题的变体进行了几次询问.下面,我在此处修改了Rcpp的答案:

Of course, there are other ways as well. Variations on this question have been asked a few times on Stack Overflow in the context of plain C++. Below I've adapted the answer here for 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

这篇关于Rcpp:按另一个向量的顺序重新排列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆