0

I'm trying to code a simple function in r using rcpp. I'm figuring out the syntax through http://adv-r.had.co.nz/Rcpp.html and used the sugar functions but could not get the following to work:

cppFunction('NumericMatrix fun(NumericMatrix x) {
    NumericMatrix dd = (exp(-(pow(x, 2)) / 2)*(3 - 6*pow(x, 2) + pow(x,4)))/sqrt(2*PI);
    return dd;
}')

Basically to apply a function in each element of a matrix. How can I make it to work?

René Schou
  • 103
  • 7
  • 2
    This is covered by 3.5 in the [Rcpp faq](http://dirk.eddelbuettel.com/code/rcpp/Rcpp-FAQ.pdf) – dww Nov 07 '16 at 17:29

1 Answers1

2

Unfortunately, matrix multiplication is not yet supported for Rcpp NumericMatrix. One option is to use Armadillo via RcppArmadillo.

# install.packages("RcppArmadillo")
Rcpp::cppFunction('arma::mat fun(const arma::mat& x) {
    arma::mat dd = (exp(-(pow(x, 2)) / 2)%(3 - 6*pow(x, 2) + pow(x,4)))/sqrt(2*PI);
    return dd;
}', depends = "RcppArmadillo")

Note % is the element-wise multiplication

coatless
  • 20,011
  • 13
  • 69
  • 84
  • Thanks for the reply. I however got an error using the code: ld: warning: directory not found for option '-L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2' ld: library not found for -lgfortran clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [sourceCpp_3.so] Error 1 – René Schou Nov 07 '16 at 16:25
  • http://thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error/ – coatless Nov 07 '16 at 16:26