Using `sourceCpp` to compile `fastLm`

前端 未结 1 1307
旧巷少年郎
旧巷少年郎 2021-02-10 00:21

I started playing around with Rcpp and would like to use the fastLm function as an example (also because it\'s useful for potential later work). I know

1条回答
  •  难免孤独
    2021-02-10 00:38

    You need to indicate dependency on RcppArmadillo with the Rcpp::depends pseudo attribute. This will take care of finding RcppArmadillo headers and link against blas, lapack etc ...

    #include 
    // [[Rcpp::depends(RcppArmadillo)]]
    
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    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 Rcpp::List::create(
            Rcpp::Named("coefficients") = coef,
            Rcpp::Named("stderr")       = stderrest
        ) ;
    
    }
    

    Also, it is very important that you use #include and not #include . RcppArmadillo.h takes care of including Rcpp.h at the right time, and order of include files is very important here.

    Also, you can return a List and drop the extern "C".

    0 讨论(0)
提交回复
热议问题