I would like to learn to use Rcpp. I went through the docs on the package's CRAN website, but i feel working on a practical example (second practical, considering convolve3) would be more helpfull .
I propose the following code, from the the robustbase package because it's neither too long nor too short, uses a combination of R types and R functions and has one of those small arithmetic iterations that are too slow in R. How would you go about Rcpp-ing it ?
scaleTau2<-function (x, c1 = 4.5, c2 = 3, consistency = TRUE, mu.too = FALSE){
n <- length(x)
medx <- median(x)
x. <- abs(x - medx)
sigma0 <- median(x.)
mu <- if (c1 > 0) {
x. <- x./(sigma0 * c1)
w <- 1 - x. * x.
w <- ((abs(w) + w)/2)^2
sum(x * w)/sum(w)
}
else medx
x <- (x - mu)/sigma0
rho <- x^2
rho[rho > c2^2] <- c2^2
if (!identical(consistency, FALSE)) {
Erho <- function(b) 2*((1-b^2)*pnorm(b)-b*dnorm(b)+b^2)-1
Es2 <- function(c2) Erho(c2*qnorm(3/4))
nEs2 <-ifelse(consistency == "finiteSample",n-2,n)*Es2(c2)
}
else nEs2 <- n
c(if (mu.too) mu, sigma0 * sqrt(sum(rho)/nEs2))
}
Please explain as much as you can.
EDIT It's really the idea of a step by step explanation of how you would go about converting a well written (and documented) R code (so at least the foundations are okay) unto an efficient implementation. The choice of the code is arguable a bit random but i think it reflects the arch-typical script on our blueprints (calls R functions that one doesn't want to translate, uses arithmetic loops....).
EDIT2 from the comments i realize this may actually be a big work to do in C++ (i didn't realize it when posting the code). In regard of this, using individual pieces as pedagogical devices is ok. I'll eventually parse the pieces together by editing the question.