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'