[Rcpp-devel] dmvnorm() of mvtnorm using RcppArmadillo

Dirk Eddelbuettel edd at debian.org
Thu Dec 19 21:19:19 CET 2019

On 20 December 2019 at 07:50, Shaami wrote:
| #include <RcppArmadillo.h>
| #include <mvtnormAPI.h>

That is not used as you call the R function.

In short, don't call the R function. I buys you nothing.  You were told to
look into using the API from that header.  I would do that if I were you.

| using namespace Rcpp;
| using namespace RcppArmadillo;
| using namespace arma;

Flattening namespaces like that is generally a bad idea.
| //[[Rcpp::depends(RcppArmadillo)]]
| //[[Rcpp::depends(mvtnorm)]]

Again, you don't use it (yet) so no reason (yet) to include this.

| //[[Rcpp::export]]

That empty line is a bad idea.

| arma::vec  dmvnormC(const arma::mat& x, const arma::vec& mean, const
| arma::mat& sigma, int give_log)
| {
|   Environment pkg = Environment::namespace_env("mvtnorm");
|   Function dmvnorm = pkg["mvtnorm"];

As above. R code runs at the speed of R code.  Calling it N times makes it N
times worse.

|   int N = x.n_rows;
|   arma::rowvec f(N);
|   for(int k=0; k<N; k++)
|     {
|       f(k) = Rcpp::as<double>(dmvnorm(x.row(k), mean,  sigma, give_log));

I would decompose this into two or three steps. Call dmvnorm() [til you know
better]. Convert to a double.  Assign the double to f(k).


|     }
|   return f;
| }

http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org

More information about the Rcpp-devel mailing list