[Rcpp-devel] Over-loading R functions

Sparapani, Rodney rsparapa at mcw.edu
Sat Mar 26 22:34:10 CET 2016


Hi Gang:

I was recently explaining to someone that functions like Rcpp::rnorm only
take scalars.  Since the R function takes vectors, the OP was asking me
why?
I didn¹t have a good answer.  This morning, I started thinking about it
and I realized this could easily be handled by over-loading (I know: that
is 
why they call me Mr. Excitement ;o)

I don¹t know if these overloads would have to be written by hand or could
be 
auto-generated.  If the latter, then I guess it is a feature request.  If
not, 
then probably a friendly suggestion.  But, here is a short example that
shows 
it is feasible if there is any doubt.

Happy Easter!

Rodney

The R transcript...
> require(Rcpp)
Loading required package: Rcpp

> sourceCpp('rnorm.cpp')

> set.seed(21)

> rnorm(6, 0, 0.01/1:2)
[1]  0.007930132  0.002611256  0.017462222 -0.006356681  0.021973895
[6]  0.002165654

> set.seed(21)

> test0(6, 0, 0.01/1:2)
[1]  0.007930132  0.002611256  0.017462222 -0.006356681  0.021973895
[6]  0.002165654

> set.seed(21)

> rnorm(6, 0:1, 0.01)
[1] 0.007930132 1.005222513 0.017462222 0.987286639 0.021973895 1.004331308

> set.seed(21)

> test0(6, 0:1, 0.01)
[1] 0.007930132 1.005222513 0.017462222 0.987286639 0.021973895 1.004331308

> set.seed(21)

> rnorm(6, 0:2, 0.01/1:2)
[1]  0.007930132  1.002611256  2.017462222 -0.006356681  1.021973895
[6]  2.002165654

> set.seed(21)

> test0(6, 0:2, 0.01/1:2)
[1]  0.007930132  1.002611256  2.017462222 -0.006356681  1.021973895
[6]  2.002165654


rnorm.cpp begin
#include <Rcpp.h>

Rcpp::NumericVector rnorm(int n, Rcpp::NumericVector mean,
Rcpp::NumericVector sd) {
  const int k_mu=mean.size(), k_sd=sd.size();
  Rcpp::NumericVector ret(n);
  for(int i=0; i<n; ++i) ret[i]=Rcpp::rnorm(1, mean[i%k_mu],
sd[i%k_sd])[0];
  return ret;
}

// [[Rcpp::export]]
Rcpp::NumericVector test0(int n, Rcpp::NumericVector mean,
Rcpp::NumericVector sd) {
  return rnorm(n, mean, sd);
}
rnorm.cpp end

rnorm.R begin
require(Rcpp)
sourceCpp('rnorm.cpp')

set.seed(21)
rnorm(6, 0, 0.01/1:2)

set.seed(21)
test0(6, 0, 0.01/1:2)

set.seed(21)
rnorm(6, 0:1, 0.01)

set.seed(21)
test0(6, 0:1, 0.01)

set.seed(21)
rnorm(6, 0:2, 0.01/1:2)

set.seed(21)
test0(6, 0:2, 0.01/1:2)

rnorm.R end





More information about the Rcpp-devel mailing list