#include <Rcpp.h>
//[[Rcpp::export]]
double muRcpp(Rcpp::NumericVector x){
int n = x.size(); // Size of vector
double sum = 0; // Sum value
// For loop, note cpp index shift to 0
for(int i = 0; i < n; i++){
// Shorthand for sum = sum + x[i]
sum += x[i];
}
return sum/n; // Obtain and return the Mean
}
muVec <- function(x){
x <- tibble::enframe(x)
a <- x %>% mutate(Aux = value/nrow(x)) %>% summarise(Mu = sum(Aux))
a$Mu
}
# Example
x <- 0:10
mean(x)
## [1] 5
x <- 0:10
base <- microbenchmark(Rcpp = muRcpp(x),
R_Vec = muVec(x),
R_base = mean(x),
times = 100)
base %>% ggplot() +
geom_boxplot(aes(x = reorder(expr, time, median), y = time, color = factor(expr)))
Rcpp really is faster than base R, however it always seem to have that initial run that it is slower than R base. I think that this is the time difference it takes to call the package and/or the function. Vectorized it is indeed slower, for it deals with much more memory, however we get information that we wouldn’t otherwise, as to what is happening inside the function.