首页 > 解决方案 > 在 Rcpp 中对命名的数字向量进行排序

问题描述

在一个函数中,我想计算数值,给它们命名并返回一个NumericVector在 Rcpp 中排序的值。我可以对向量进行排序(使用this),但值名称的顺序保持不变。

library(Rcpp)
x <- c(a = 1, b = 5, c = 3)
cppFunction('
NumericVector foo(NumericVector x) {
  std::sort(x.begin(), x.end());
  return(x);
}')
foo(x)
## a b c 
## 1 3 5 

我希望函数返回这个:

## a c b 
## 1 3 5 

可能吗?我怎样才能做到这一点?

标签: rrcpp

解决方案


使用 Dirk 在他的评论中给出的提示,我发现 names ofx只是另一个向量。因此,我搜索了使用另一个向量对向量进行排序。使用这个 SO 答案我想出了以下两个解决方案:

library(Rcpp)
x = c(a = 1, b = 5, c = 3, d = -3.2)

cppFunction('
NumericVector foo1(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 return x[idx];
}')

foo1(x)

##    d    a    c    b 
## -3.2  1.0  3.0  5.0 


cppFunction('
NumericVector foo2(NumericVector x) {
 IntegerVector idx = seq_along(x) - 1;
 //// Ordered indices based on x:
 std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
 //// Get the names of x:
 CharacterVector names_of_x = x.names();
 //// y vector is sorted x 
 NumericVector y = x[idx];
 //// Assign sorted names to y vector as names
 y.attr("names") = names_of_x[idx];
 return y;
}')

foo2(x)

##    d    a    c    b 
## -3.2  1.0  3.0  5.0 

推荐阅读