I'm new for Rcpp
, and in my code, I need use the R
function optim
in Rcpparmadillo. I referred to the example what I was trying. I read the very similar question in Calling R's optim function from within C++ using Rcpp, but it is quite different in that there are other variables x
and y
. That is, I need to optimize the function with respect to b but it depends on variables x
and y
.
Hear's the code that I am trying.
#include <RcppArmadillo.h>
using namespace arma;
using namespace Rcpp;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
vec fr(vec b, vec x, double y){
vec a1 = b.t()*x- y;
return a1;
}
// [[Rcpp::export]]
vec optim_rcpp(const vec& init_val, vec x, double y){
Rcpp::Environment stats("package:stats");
Rcpp::Function optim = stats["optim"];
Rcpp::List opt_results = optim(Rcpp::_["par"] = init_val,
Rcpp::_["fn"] = Rcpp::InternalFunction(&fr(init_val,x,y)),
Rcpp::_["method"] = "BFGS");
vec out = Rcpp::as<vec>(opt_results[0]);
return out;
}
or
// [[Rcpp::export]]
vec optim_rcpp(const vec& init_val, vec x, double y){
Rcpp::Environment stats("package:stats");
Rcpp::Function optim = stats["optim"];
Rcpp::List opt_results = optim(Rcpp::_["par"] = init_val,
Rcpp::_["fn"] = Rcpp::InternalFunction(&fr),
Rcpp::_["method"] = "BFGS");
vec out = Rcpp::as<vec>(opt_results[0]);
return out;
}
Please give me any comment! Thank you!