(I’m assuming you are using stats::optim. There are actually other functions with that name in other packages — pasting in your full reprex output would clear up this point!)
From the documentation for optim():
optim(par, fn, gr = NULL, …,
method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN",
"Brent"),
lower = -Inf, upper = Inf,
control = list(), hessian = FALSE)
This tells us that:
- The first argument (
par) must be the initial values to optimize over
- The second argument (
fn) must be the function to optimize
- The third argument is optional with a default value of
NULL
-
Then come the
...("dots") where you supply any other arguments for the function you passed as fn
- After the
... is the method parameter, which (since it follows ...) must be supplied with a name
You seem to be calling optim() with:
optim(lambda = lambda.init, cost, phi = phi, Sd = Sd, method = "CG")
Is lambda.init meant to be the initial values you want to optimize over? If so, you need to either pass it by position (no parameter name, must be the first argument), or pass it with the correct parameter name of par:
# Pass `par` by position
optim(lambda.init, cost, phi = phi, Sd = Sd, method = "CG")
# If you pass `par` by name it can appear out of order,
# but note that some people may find this style a bit
# confusing! (wait, what's the first argument?)
optim(cost, par = lambda.init, phi = phi, Sd = Sd, method = "CG")
For more background on how to pass arguments into R functions, this chapter of Roger Peng's R Programming for Data Science is a good place to start: https://bookdown.org/rdpeng/rprogdatascience/functions.html