Skip to content

Instantly share code, notes, and snippets.

@twolodzko
Created March 26, 2018 06:27
Show Gist options
  • Save twolodzko/ec8f556afc38da1b22fcafb96c8e90c0 to your computer and use it in GitHub Desktop.
Save twolodzko/ec8f556afc38da1b22fcafb96c8e90c0 to your computer and use it in GitHub Desktop.
Runnng lengths in Rcpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List cpp_rle2(
const NumericVector& x,
const double h = 0,
const double eps = 1e-16
) {
int n = x.length();
if (n == 1) {
return Rcpp::List::create(
Rcpp::Named("lengths") = wrap(1),
Rcpp::Named("group") = wrap(1),
Rcpp::Named("changepoints") = wrap(1)
);
}
std::vector<int> labels(n), lengths(n);
std::vector<int> changes;
int tmpCount = 1;
int prevStart = 0;
labels[0] = 1;
changes.push_back(1);
for (int i = 0; i < (n-1); i++) {
if ( std::abs((x[i] + h) - x[i+1]) <= eps ) {
tmpCount += 1;
labels[i+1] = labels[i];
} else {
for (int j = prevStart; j <= i; j++)
lengths[j] = tmpCount;
tmpCount = 1;
prevStart = i+1;
labels[i+1] = labels[i]+1;
changes.push_back(i+2);
}
}
for (int j = prevStart; j < n; j++)
lengths[j] = tmpCount;
return Rcpp::List::create(
Rcpp::Named("lengths") = lengths,
Rcpp::Named("group") = labels,
Rcpp::Named("changepoints") = changes
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment