I'm trying to optimize a sorting function in R using C++ through the Rcpp package. The function that I'm trying to mimic is sort(x, decreasing = TRUE, na.last = TRUE)
. I've been able to implement the first argument decreasing = TRUE
just fine with the following code:
library(Rcpp)
x <- c(3, 7, 21, 6, NA, 1, 8, 7)
# base R sorting
sort(x, decreasing = TRUE, na.last = TRUE)
# [1] 21 8 7 7 6 3 1 NA
# Simple Rcpp sorting function
cppFunction("NumericVector sort_cpp(NumericVector x, bool decreasing = false) {
NumericVector sorted = clone(x).sort(decreasing);
return sorted;
}")
sort_cpp(x, decreasing = TRUE)
# [1] NA 21 8 7 7 6 3 1
I'm not well versed in C++ or the Rcpp package enough to be able to place NA values last in all cases. When I set decreasing
to FALSE, it will place the NA values at the end by default, but when it gets reversed (set to TRUE), it flips the whole vector around and the NA values go at the front of the vector. I've tried a couple of things with limited success (again, very novice in C++), and was able to get something running in a C++ shell but I haven't been able to successfully code it into R. This is mostly copied and pasted from this question:
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
int n, k = 4, j; // k is number of elements
double x = -0.0;
double i = 0;
double swap = 0;//used in the function as a place holder and used for swapping between other variables
double a[100] = { (1/x) + (1/i), 2.3, 1/x *0, 1/i };//array of double elements // 1/i * 0 is NaN
//(1 / i) * 0
for (n = 0; n < (k - 1); n++) // for loop consists of variables and statements in order to arrange contents of array
{
for (j = 0; j < k - n - 1; j++)
{
if (!std::isnan(a[j + 1]) && std::isnan(a[j]) || (a[j] > a[j + 1]))
{
swap = a[j];
a[j] = a[j + 1];
a[j + 1] = swap;
}
}
}
cout << "The list of sorted elements within the array, is: " << endl; /* Output message to user */
for (int i = 0; i < k; i++)// Loop up to number of elements within the array
{
cout << a[i] << " ";/* Output contents of array */
}
cout << endl; //new line
return 0;
}
Is there a way to get this into R using the Rcpp package, or equivalent?