Reputation: 1241
Question:
I am using optim
to optimise my function. However, my function have 2 paramters, first is a scalar, second is a dynamic length vector.
I initialized parameters with a list and then pass into optim
function. Raise the following error, it seems par
in optim
can only get a vactor input? Since my second parameter has dynamic length, it's difficult to use a vector of parameters and then slice with y <- para_vector[slice]
to pass them to y
.
For instance:
# I dont know the length of second elements
para <- c(1,3,2, ... ,283)
x <- para[1]
# I can't slice the vector and pass value to y
y <- para[2:?]
Code:
obj <- function(para){
### input:
### para is a list with 2 elements.first element is scalar, second element is vector
# x is a scalar, stored in the first position of para list
x <- para[[1]]
# y is a vector with unfixed length, so I store it in the second element in a list
y <- para[[2]]
value <- x^2 + sum(y^2)
return(value)
}
para_initial = list(1,c(0,1))
optim(par = list(1,c(0,1)),fn = obj)
Output:
Error in optim(par = list(1, c(0, 1)), fn = obj) : (list) object cannot be coerced to type 'double'
Upvotes: 0
Views: 1259
Reputation: 1829
You will have to change your objective function because, as Bhas said, optimization solvers require parameters as vectors. If it is difficult to change the obj()
function, you can write a wrapper for it that splits the input vector into a list.
obj_wrap <- function(x) {
obj(list(x[1], x[2:length(x)])) ## CORRECTED
}
Now sove it by applying optim
to this function.
para_initial = list(1,c(0,1))
optim(unlist(para_initial), fn = obj_wrap)
## $par
[1] 4.575264e-05 1.710995e-05 -5.172657e-05
## ...
which looks a bit clumsy, but would be possible and gives a correct result..
Upvotes: 1