Skip to content

Instantly share code, notes, and snippets.

@jjallaire
Created November 1, 2012 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjallaire/3993978 to your computer and use it in GitHub Desktop.
Save jjallaire/3993978 to your computer and use it in GitHub Desktop.
Rcpp engine for knitr
```{r engine='Rcpp'}
int fibonacci(const int x) {
if (x == 0) return(0);
if (x == 1) return(1);
return (fibonacci(x - 1)) + fibonacci(x - 2);
}
```
```{r engine='Rcpp', Rcpp.plugin='RcppArmadillo'}
List fastLm(NumericVector yr, NumericMatrix Xr) {
int n = Xr.nrow(), k = Xr.ncol();
arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy
arma::colvec y(yr.begin(), yr.size(), false);
arma::colvec coef = arma::solve(X, y); // fit model y ~ X
arma::colvec resid = y - X*coef; // residuals
double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
// std.error of estimate
arma::colvec stderrest = arma::sqrt(
sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );
return List::create(Named("coefficients") = coef,
Named("stderr") = stderrest
);
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment