1

How to use the varargs functions of the R language, as is the case of the optim function?

Consider the code below where I want to maximize the log-likelihood function verossimilhanca:

#include <Rcpp.h>
#include <RInside.h>

using namespace Rcpp;

// [[Rcpp::export]]

double verossimilhanca(Function pdf, NumericVector par, NumericVector x){
  NumericVector log_result = log(pdf(par,x));
  double soma =0;
  for(int i = 0; i < log_result.size(); i++){
    soma += log_result[i];
  }

  return -1*soma;
} 
// [[Rcpp::export]]
List bootC(NumericVector x, NumericVector init_val){ 
  Rcpp::Environment stats("package:stats"); 
  Rcpp::Function optim = stats["optim"];    

  R["my_objective_fn"] = Rcpp::InternalFunction(&verossimilhanca);

  Rcpp::List opt_results = optim(Rcpp::_["par"]  = init_val,
                                 Rcpp::_["fn"]     = Rcpp::InternalFunction(&verossimilhanca),
                                 Rcpp::_["method"] = "BFGS", x);

  return opt_results;
  // x is a data vetor.
}

In summary, I have a log-likelihood function and I want to maximize this function and x is my data set. I know that RInside allows me to create instances of R in C++ but I want to solve this problem only by using the Rcpp.h library without resorting to RInside.h.

Acorn
  • 24,970
  • 5
  • 40
  • 69
Pedro Rafael
  • 492
  • 4
  • 11
  • In short, bad idea. You will get _optmization mostly at the same speed as from R_ with more as you call it from C++. If you want C++ access, look at (the development version of) nloptr (which you can access from C). – Dirk Eddelbuettel May 08 '18 at 21:47
  • Also, for standard Rcpp use from R you never want `RInside.h`. – Dirk Eddelbuettel May 08 '18 at 21:48
  • Thanks for the tip. She will be very helpful. But just to kill my curiosity about a question I have: I know it's possible to make use of an R function and call this function for C ++ code using Rcpp. If this function of R accepts argvar (variable arguments) (...), is there any way to import this function into C ++ via Rcpp and this function prezervar this characteristic, ie is it possible to make use of a (variable arguments) (...) of the imported function in C++? – Pedro Rafael May 08 '18 at 23:51

1 Answers1

0

Replace x with Rcpp::_["x"] = x in the arguments of optim function. It bothers me too until I find the answer of @coatless.

T. Yao
  • 1