Created
November 1, 2012 14:33
-
-
Save jjallaire/3993978 to your computer and use it in GitHub Desktop.
Rcpp engine for knitr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```{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