0

I am trying to do something like the following via Rcpp

In C++

#include<Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double func(double x, double y) {
  return x*y;
}

In R:

g<-function(x){func(x,1)}
integrate(g,lower=0, upper=2)

An error message is returned as "Error in func(x, 1) : expecting a single value." It seems that the function "x*y" is not passed to R from C++ in such a way that it can be used for integration in R. Can someone give me some ideas on how to make it work? (I know such integration can be done directly in C++, but I have to do the integration in R).

Thanks in advance for all helpful comments!

Panda
  • 1
  • The duplicate was asked for RcppArmadillo, but the answer applies equally to Rcpp. – Dirk Eddelbuettel Nov 28 '16 at 04:31
  • Actually, your error is simpler. From `help(integrate)` on the first argument: _an R function taking a numeric first argument and returning a numeric vector of the same length. Returning a non-finite element will generate an error._ So your `func()` seems. – Dirk Eddelbuettel Nov 28 '16 at 04:36
  • It seems `integrate` assumes that your function can take a vector, not a single value. Change your C++ code as `NumericVector func(NumericVector x, double y) { return x*y; }`, then it will work out. – Kota Mori Nov 28 '16 at 08:41
  • Thanks for your comments! That works great and solves the problem. – Panda Nov 28 '16 at 09:26

0 Answers0