Reputation: 33
I define the output vector as numeric:
`surv <- vector("numeric", 38)`
The input for the function is Np, a numeric vector, and a variable S to be optimized.
I then run the following code:
'dif <- function(S){
(Np[x] - (Np[x-1]*S + Np[x-4]*0.7*S^4))^2
}
surv[x] <- optimize(dif, c(0, 1), maximum = FALSE, tol = 0.1)
}'
The code runs successfully and I can plot surv and apply ksmooth to it without a problem, but when I try to do further computations with the vector surv, I get the following message:
"Error in ....... : non-numeric argument to binary operator".
I have tried "unlist(surv)" and "as.numeric(surv)" but still encounter the same problem.
Can anyone tell me what I am doing wrong and how to correct this so that surv is a numeric vector that I can use in further computations? Thanks
Upvotes: 0
Views: 53
Reputation: 33
I have solved the problem. My error was in a) not reading the R documentation on 'optimize' carefully and, as a result, b)assuming that the output from 'optimize' was a single value i.e. the minimum for the objective function. Having now established that the output is a list consisting of the objective and the minimum, I can extract the elements I want simply using xxx$minimum.
I am surprised, however, that despite this problem in my original code, saving the results of optimizing the defined function as elements of a vector (surv) did not generate an error and that a plot of 'surv' produced a plot of the minimums, which is what I had expected. Nevertheless, the key message for me is read the fine print!
Upvotes: 1