Using Optim() and Optimize() functions in R


#1

Hi

I have been trying to use Optim() or Optimize() function to minimize the sum of absolute forecast errors.

I have 2 vectors, each of length 28, 1 containing forecast data and the other containing the actual data for the last 28 days. I have created an objective function like so :

fn <- function(fcst, act, par) {
sum(abs(act - (fcst * par)))}

Using the optmize() function like so :

xmin1 <- optimize(fn, c(0.5, 1.5), fcst = fcst, act = act)

I get the correct value for ‘par’ - no problems.

> xmin1
$minimum
[1] 0.92235

$objective
[1] 3630.399

However, when I use the optim() function like so :

xmin <- optim(par = c(0.1, 1.9), fn, fcst = fcst, act = act)

I get 2 values for par like this :-

> xmin
$par
[1] 0.9223822 0.9191707

$value
[1] 3623.823

$counts
function gradient 
95 NA

$convergence
[1] 0

$message
NULL

The question is why do I get 2 values for the single parameter par using optim() function. Shouldn’t I be getting only one (1) value as I do for the optimize() function?

Also, in either case, I get marginally different values for the parameter values depending upon the initial values of the parameter - should this be dependent upon the initial values when this objective function is essentially unimodal?

The fcst and act vectors are here :

fcst <- c(3434.23, 3434.23, 3232.4, 1894.63, 1989.23, 3827.71, 3827.71, 3827.71, 3434.23, 1984.42, 1894.63, 1989.23, 3827.71, 3827.71, 3827.71, 3827.71, 3625.88, 2288.11, 1989.23, 3434.23, 3434.23, 3434.23, 3434.23, 3232.4, 2288.11, 2382.71, 3827.71, 3827.71)

act <- c(3194.62, 3109.93, 2991.44, 1741.49, 1935.07, 3100.84, 3169.39, 3170.24, 2613.81, 1947.35, 1820.63, 1765.62, 3397.48, 3501.14, 3444.14, 3589.24, 3263.55, 2153.49, 2159.85, 3237.94, 3345.7, 3246.66, 3195.58, 3001.53, 2073.76, 2419.29, 3530.62, 3455.71)

Best regards

Deepak Agarwal


#2

Could you please turn this into a self-contained reprex (short for minimal reproducible example)? It will help us help you if we can be sure we’re all working with/looking at the same stuff.

If you’ve never heard of a reprex before, you might want to start by reading the tidyverse.org help page. The reprex dos and don’ts are also useful.