Using R function in Rstan


#1

To use the Stan software in R, I use Rstan. I created a .stan file and specifed the data, parameters, transformed parameters and model blocks. The problem is that my model is based on differential equations that I solved in R (with Rcpp to be specific). Therefore, to write the likelihood function in the “model” block, I need to call a R function defined in my R script.
How can I call a R function in .stan file?


#2

You can’t (largely due to the need for autodiff). If you can write the solution analytically in R, you can write it with a user-defined Stan function. If you are doing it numerically, you can do it with integrate_ode_something in Stan depending on whether it is stiff or non-stiff.


#3

Really? I already transformed my R function into a C++ function using Rcpp package, so don’t you think we can find a way to use it in Rstan?


#4

Can you paste your c++ function in here so we see what you’re working with?


#5

I actually just import my R function into a C++ script using the Rcpp package in R.
My R function is called my_fun22().

// [[Rcpp::export]]
void my_fun22(Rcpp::NumericVector &x, const double t){
  Function f("mod_cpp");
  x=f(_["t"]=t,_["x"]=x);
}

#7

Yeah, the issue is that Stan internally works with fully templated C++ functions which allows Stan to calculate the derivatives of the function w.r.t. the model parameters as needed. For example here’s the code for max;

template <typename T1, typename T2>
inline typename boost::math::tools::promote_args<T1, T2>::type fmax(
    const T1& x, const T2& y) {
  if (is_nan(x))
    return y;
  if (is_nan(y))
    return x;
  return x > y ? x : y;
}

Maybe you know enough C++ to write your function into something like that, but maybe it’s easier to re-write it into Stan language and just use the integrator in Stan (as Ben suggested). So describe your problem and you’ll get better suggestions.


#8

Thanks sakrejda, I asked a new questions by explaining my problem in more details.