C++ Rcpp:按另一个向量的顺序重新排列一个向量
我是Rcpp的新手。我需要按照另一个向量C++ Rcpp:按另一个向量的顺序重新排列一个向量,c++,r,sorting,rcpp,C++,R,Sorting,Rcpp,我是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\u index来查找B的顺序,但是我无法按照B的顺序排列A 我该怎么做呢?你应该能够使用arma::sort\u index来实现这一点,你在文章中提到了: #include <R
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\u index
来查找B
的顺序,但是我无法按照B
的顺序排列A
我该怎么做呢?你应该能够使用
arma::sort\u 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)
*/
当然,还有其他方法。这个问题的变化已经被问了几次在堆栈溢出的背景下,平原C++。下面我对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)
*/
您应该能够为此使用
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)
*/
当然,还有其他方法。这个问题的变化已经被问了几次在堆栈溢出的背景下,平原C++。下面我对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)
*/
看,看,看