Используя подсказку, которую Дирк дал в своем комментарии, я понял, что имена x
- это просто еще один вектор. Итак, я искал сортировку вектора, используя другой вектор. Используя этот 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