Here is an attempt to translate a R function to Rcpp. The goal is to group every n observations together (of a numeric vector) and calculate the mean.
On big'ish vectors the R function is almost two order of magnitude slower (when n is small). But I wonder:
- If there are even more speed to be gained.
- There are any elements of bad or (horrible) practice.
mean_every_n <- function(x, n=5L) {
grp <- (seq_along(x) - 1 ) %/% n
ave(x, grp, FUN = \(y) mean(y, na.rm = TRUE))
}
NumericVector mean_every_n(const NumericVector x, int n) {
const int nx = x.size();
double csum = 0; // cumulative sum
double nnas = 0; // number of NAs
NumericVector out(nx);
for (int i = 0; i < nx; i++) {
if (NumericVector::is_na(x[i])) nnas++; else csum += x[i];
bool reached_end = (i == (nx-1));
if ((i+1) % n == 0 || reached_end) {
if (reached_end && (i+1) % n > 0) n = (i+1) % n;
if (nnas < n) {
double res = csum / (n - nnas);
for (int j = 0; j < n; j++) out[i - j] = res;
} else {
for (int j = 0; j < n; j++) out[i - j] = NA_REAL;
}
csum = 0, nnas = 0;
}
}
return out;
}
Inspired by a SO question.