This package uses Rcpp to connect the R system to the GNU GSL, a collection of numerical routines for scientific computing, particularly its vector and matrix classes.
lm()
for OLS
regressionThe fastLm()
function included
as file src/fastLm.cpp
in the package:
#include <RcppGSL.h>
#include <gsl/gsl_multifit.h>
#include <cmath>
// [[Rcpp::export]]
::List fastLm(const RcppGSL::Matrix &X, const RcppGSL::Vector &y) {
Rcpp
int n = X.nrow(), k = X.ncol();
double chisq;
::Vector coef(k); // to hold the coefficient vector
RcppGSL::Matrix cov(k,k); // and the covariance matrix
RcppGSL
// the actual fit requires working memory we allocate and free
*work = gsl_multifit_linear_alloc (n, k);
gsl_multifit_linear_workspace (X, y, coef, cov, &chisq, work);
gsl_multifit_linear (work);
gsl_multifit_linear_free
// assign diagonal to a vector, then take square roots to get std.error
::NumericVector std_err;
Rcpp= gsl_matrix_diagonal(cov); // need two step decl. and assignment
std_err = Rcpp::sqrt(std_err); // sqrt() is an Rcpp sugar function
std_err
return Rcpp::List::create(Rcpp::Named("coefficients") = coef,
::Named("stderr") = std_err,
Rcpp::Named("df.residual") = n - k);
Rcpp
}
This example comes from the complete
example package included in RcppGSL and is from the
file inst/examples/RcppGSLExample/src/colNorm.cpp
#include <RcppGSL.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
// [[Rcpp::export]]
::NumericVector colNorm(const RcppGSL::Matrix & G) {
Rcppint k = G.ncol();
::NumericVector n(k); // to store results
Rcppfor (int j = 0; j < k; j++) {
::VectorView colview = gsl_matrix_const_column (G, j);
RcppGSL[j] = gsl_blas_dnrm2(colview);
n}
return n; // return vector
}
On CRAN and here.
Dirk Eddelbuettel and Romain Francois
GPL (>= 2)