[R] NA return to NLM routine
Berend Hasselman
bhh at xs4all.nl
Sat Dec 1 22:25:39 CET 2012
On 30-11-2012, at 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
>
if you do
a <- NA
str(a)
you'll see that a is a logical. And that is an invalid value for the function to return.
When you do things such as NA+0 or -NA you get a numeric value NA and that is a non-finite value which is why you get the warning..
Instead of NA you could return something like .Machine$double.xmax .
Or use constrOptim as advised.
Berend
> 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.
>
> 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