René Schou - 9 months ago 89

R Question

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?

Answer Source

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