[R] NA return to NLM routine

Uwe Ligges ligges at statistik.tu-dortmund.de
Sat Dec 1 19:53:19 CET 2012



On 30.11.2012 23:55, Mac Gaulin wrote:
> Hello,
>
> I am trying to understand a small quirk I came across in R. The
> following code results in an error:
>
> k <- c(2, 1, 1, 5, 5)
> f <- c(1, 1, 1, 3, 2)
> loglikelihood <- function(theta,k,f){
>      if( theta<1 && theta>0 )
>          return(-1*sum(log(choose(k,f))+f*log(theta)+(k-f)*log(1-theta)))
>      return(NA)
> }
> nlm(loglikelihood ,0.5, k, f )
>
> Running this code results in:
> Error in nlm(logliklihood, 0.5, k, f) :
>    invalid function value in 'nlm' optimizer
>
> However if the line return(NA) is changed to return(-NA) or even
> return(1*NA) or return(1/0), the code works. Is this expected
> behavior? The nlm help file says not NA or not NaN are acceptable
> values but I don't understand what that means.

Your function must return finite numbers, that means infinite numbers, 
NA nor NaN are not allowed and you experienced what happens if you do that.

Please see ?constrOptim or other appropriate functions for constrained 
optimization problems.

Uwe Ligges

>
> Thank you for your time,
> Mac Gaulin
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list