[R] invalid function value in 'nlm' optimizer

Duncan Murdoch murdoch.duncan at gmail.com
Tue Apr 28 12:40:10 CEST 2015

On 28/04/2015 2:43 AM, Hanze Zhang wrote:
> Hi, R users,
> I am using nlm function to get the MLE of parameter alpha and lambda from a
>  parametric survival model (Weibull distribution). However, this message
> always came out: ' invalid function value in 'nlm' optimizer'. Could anyone
> help me? Code is
> project<-read.table(file="C://data.txt", header=T, as.is=T)
> names(project)
> attach(project)
> x<-time
> delta<-ind
> # -log likelihood
> #alpha<-theta[1]
> #lambda<-theta[2]
> ln<-function(theta)
>   {
>  -sum(delta)*log(theta[1]*theta[2])-sum(delta)*(theta[1]-1)*log(x[delta==1])+theta[2]*sum(x^theta[1])
> }
> #MLE
> nlm(ln,theta<-c(1,1),hessian=TRUE)

You are taking logs of parameters.  Probably the optimizer is setting
the parameters to negative values, and so the log returns NaN.

You can avoid this by testing your parameters on input, and always
returning a valid number.  There are lots of ways to do this: One
strategy is to return +Inf for invalid values; another is to move the
parameter to the nearest boundary, and apply a penalty according to how
far you moved it.  Or just take the absolute value of the parameter.  Or
reparametrize so that illegal values aren't possible.

Duncan Murdoch

More information about the R-help mailing list