Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The optim function in R can be used with Rcpp by writing an Rcpp function that performs the optimization task and returning the optimized parameters to R. Here is an example:

  1. Write an Rcpp function that takes in the parameter vector and returns the negative log likelihood (or any other scalar objective function) value:

```{cpp}

include <rcpp.h>

using namespace Rcpp;

// Define the objective function double objectivefunction(NumericVector param, NumericVector data) { double mu = param[0]; double sigma = param[1]; double n = data.size(); double ll = -0.5 * n * log(2 * MPI) - (n/2)log(sigmasigma) - sum(pow(data - mu, 2))/(2*pow(sigma, 2)); return(-ll); // Return the negative log-likelihood }

// Define the Rcpp wrapper function // [[Rcpp::export]] NumericVector optimizercpp(NumericVector theta, NumericVector data) { // Define the optimization routine using the "optim" function in R List result = optim(theta, objectivefunction, data, method = "BFGS", control = list(fnscale = -1)); // Return the optimized parameters return(result["par"]); }


2. Compile the Rcpp function using the `sourceCpp` function in R:

```{r}
library(Rcpp)
sourceCpp("optim_rcpp.cpp")
  1. Call the Rcpp function from R to optimize the objective function:

```{r}

Generate some data

set.seed(123) data <- rnorm(100, mean = 2, sd = 1)

Set initial parameter values

theta <- c(mean(data), sd(data))

Call the Rcpp function to optimize the objective function

optimaltheta <- optimizercpp(theta, data) optimal_theta ```

This will return the optimized mean and standard deviation of the normal distribution that best fits the generated data.