Rcpp Version 0.9.10
lmArmadillo.R
Go to the documentation of this file.
00001 #
00002 # lm() via Armadillo -- improving on the previous GSL solution
00003 #
00004 # Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois
00005 #
00006 # This file is part of Rcpp.
00007 #
00008 # Rcpp is free software: you can redistribute it and/or modify it
00009 # under the terms of the GNU General Public License as published by
00010 # the Free Software Foundation, either version 2 of the License, or
00011 # (at your option) any later version.
00012 #
00013 # Rcpp is distributed in the hope that it will be useful, but
00014 # WITHOUT ANY WARRANTY; without even the implied warranty of
00015 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 # GNU General Public License for more details.
00017 #
00018 # You should have received a copy of the GNU General Public License
00019 # along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.
00020 
00021 suppressMessages(require(Rcpp))
00022 suppressMessages(require(inline))
00023 
00024 lmArmadillo <- function() {
00025     src <- '
00026 
00027     Rcpp::NumericVector yr(Ysexp);
00028     Rcpp::NumericVector Xr(Xsexp);
00029     std::vector<int> dims = Xr.attr("dim") ;
00030     int n = dims[0], k = dims[1];
00031 
00032     arma::mat X(Xr.begin(), n, k, false);       // use advanced armadillo constructors
00033     arma::colvec y(yr.begin(), yr.size());
00034 
00035     arma::colvec coef = solve(X, y);            // fit model y ~ X
00036 
00037     arma::colvec resid = y - X*coef;            // to compute std. error of the coefficients
00038     double sig2 = arma::as_scalar(trans(resid)*resid)/(n-k);    // requires Armadillo 0.8.2 or later
00039     arma::mat covmat = sig2 * arma::inv(arma::trans(X)*X);
00040 
00041     Rcpp::NumericVector coefr(k), stderrestr(k);
00042     for (int i=0; i<k; i++) {                   // this is easier in RcppArmadillo with proper wrappers
00043         coefr[i]      = coef[i];
00044         stderrestr[i] = sqrt(covmat(i,i));
00045     }
00046 
00047     return Rcpp::List::create( Rcpp::Named( "coefficients", coefr),
00048                                Rcpp::Named( "stderr", stderrestr));
00049     '
00050 
00051     ## turn into a function that R can call
00052     fun <- cfunction(signature(Ysexp="numeric", Xsexp="numeric"),
00053                      src,
00054                      includes="#include <armadillo>",
00055                      Rcpp=TRUE,
00056                      cppargs="-I/usr/include",
00057                      libargs="-larmadillo -llapack")
00058 }
00059 
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Defines