Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp sort descending

Tags:

c++

r

rcpp

I cannot sort in descending order using Rcpp

Sort in ascending order:

NumericVector sortIt(NumericVector v){
    std::sort(v.begin(), v.end());
    return v;
}

Attempt to sort in descending order:

NumericVector sortIt(NumericVector v){
    std::sort(v.begin(), v.end(), std::greater<int>()); // does not work returns ascending
    return v;
}

and

NumericVector sortIt(NumericVector v){
    std::sort(numbers.rbegin(), numbers.rend()); // errors
    return v;
}
like image 691
JohnCoene Avatar asked Jun 26 '26 22:06

JohnCoene


1 Answers

This functionality has since been added (Rcpp version >= 0.12.7) to the Vector member function sort. This is necessary for sorting CharacterVector objects in particular (either ascending or descending) because the underlying element type requires special handling, and is incompatible with std::sort + std::greater (as well as certain other STL algorithms).

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::CharacterVector char_sort(Rcpp::CharacterVector x) {
    Rcpp::CharacterVector res = Rcpp::clone(x);
    res.sort(true);
    return res;
}

// [[Rcpp::export]]
Rcpp::NumericVector dbl_sort(Rcpp::NumericVector x) {
    Rcpp::NumericVector res = Rcpp::clone(x);
    res.sort(true);
    return res;
}

Note the use of clone to avoid modifying the input vector.


char_sort(c("a", "c", "b", "d"))
# [1] "d" "c" "b" "a"

dbl_sort(rnorm(5))
# [1]  0.8822381  0.7735230  0.3879146 -0.1125308 -0.1929413
like image 97
nrussell Avatar answered Jun 29 '26 11:06

nrussell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!