[在函数中,我想计算数值,给它们命名,然后在Rcpp中返回排序后的NumericVector
。我可以对向量进行排序(使用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
有可能吗?我该如何实现?
[使用Dirk在他的评论中给出的提示,我发现x
的名称只是另一个向量。因此,我搜索了使用另一个向量对向量进行排序的方法。使用this SO answer,我提出了以下两种解决方案:
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