Если вы действительно хотите снизить производительность, используйте Rcpp.Пользовательские циклы - отличный пример использования C ++, особенно когда ваша функция довольно проста.
Первые результаты, затем код:
microbenchmark::microbenchmark(
minmax = zoo::rollapply(aa, width=100, FUN=minmax, fill=NA),
dblmax = zoo::rollmax(aa, k=100, fill=NA) + zoo::rollmax(-aa, k=100, fill=NA),
cminmax = crollapply(aa, width=width), times = 10
)
Unit: milliseconds
expr min lq mean median uq max neval cld
minmax 154.04630 162.728871 188.198416 173.13427 200.928005 298.568673 10 c
dblmax 37.38127 38.541603 44.818505 41.42796 50.001888 61.024250 10 b
cminmax 2.31766 2.363676 2.406835 2.39237 2.438109 2.512162 10 a
C ++ / Rcpp код:
#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;
// [[Rcpp::export]]
std::vector<double> crollapply(std::vector<double> aa, int width) {
if(width > aa.size()) throw exception("width too large :(");
int start_offset = (width-1) / 2;
int back_offset = width / 2;
std::vector<double> results(aa.size());
int i=0;
for(; i < start_offset; i++) {
results[i] = NA_REAL;
}
for(; i < results.size() - back_offset; i++) {
double min = *std::min_element(&aa[i - start_offset], &aa[i + back_offset + 1]);
double max = *std::max_element(&aa[i - start_offset], &aa[i + back_offset + 1]);
results[i] = max - min;
}
for(; i < results.size(); i++) {
results[i] = NA_REAL;
}
return results;
}
R код:
library(dplyr)
library(zoo)
library(microbenchmark)
library(Rcpp)
sourceCpp("~/Desktop/temp.cpp")
minmax <- function(x) max(x) - min(x)
aa <- runif(1e4)
width <- 100
x1 <- zoo::rollapply(aa, width=width, FUN=minmax, fill=NA)
x3 <- crollapply(aa, width=width)
identical(x1,x3)
width <- 101
x1 <- zoo::rollapply(aa, width=width, FUN=minmax, fill=NA)
x3 <- crollapply(aa, width=width)
identical(x1,x3)
microbenchmark::microbenchmark(
minmax = zoo::rollapply(aa, width=100, FUN=minmax, fill=NA),
dblmax = zoo::rollmax(aa, k=100, fill=NA) + zoo::rollmax(-aa, k=100, fill=NA),
cminmax = crollapply(aa, width=width), times = 10
)