Skip to content

[Rcpp-devel] Rcpp sugar for double?

3 messages · Eridk Poliruyt, Romain Francois, Dirk Eddelbuettel

#
Hi, I just tried to calculate the density of a normal variable using dnorm.
I found that if the input is of type NumericVector, then it was fine. But
if the input is of type double, it yielded error in compilation. For
example:

 // [[Rcpp::export]]
NumericVector test5(NumericVector x)
{
  NumericVector y = dnorm(x,5.0,2.0,true);
  return(y);
}

and

// [[Rcpp::export]]
double test6(double x)
{
  double y = dnorm(x,5.0,2.0,true);
  return(y);
}

May I ask why and how can I calculate this density (and call other common
functions like dbeta, dt, beta, gamma, lbeta, lgamma, etc...) on double
input?

Many thanks,
Eridk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20170222/61f9ac15/attachment.html>
#
Hello, 

Functions in sugar only apply to vectors. 

For a single value, you?d have to use the dnorm function in the R:: namespace: 

// [[Rcpp::export]]
double test6(double x){
  double y = R::dnorm(x,5.0,2.0,true);
  return y;
}
[1] -2.112086
[1] -2.112086


Romain
#
Eridk,

See these Rcpp Gallery article from 2012 for worked examples:

 -  http://gallery.rcpp.org/articles/using-rmath-functions/  
    has an example on pnorm that applies to your dnorm case
    
 -  http://gallery.rcpp.org/articles/random-number-generation/
    discusses the RNGs, but the d/p/q functions behave the same way.

You can search at the Gallery too ...  

So we have all the scalar functions in the R:: namespace, sugar ones in
Rcpp::, you can of course call the R functions as well (though I'd use R::(
plus you get access from Armadillo, Boost, GSL, ... via other packages.

But you need to look closely at the signatures of functions you are calling.
Those expecting a 'double' cannot magically be resolved with a
'Rcpp::NumericVector' as those are different types.

Dirk