R – Passing a function argument through R-function nlm

nlmr

I am probably being unreasonable asking for help debugging a program, but I have spent a day and a half on this pretty simple bit of code and have run out of ideas. I am trying to optimize a function called "log.pr.data" with respect to its first argument.

Because the function optimize requires you to set bounds on the argument I decided to use nlm which only requires a starting point. I have checked with simple examples that nlm is indeed able to pass functions as arguments. My problem is that I am unable to pass a function as an argument in this particular case.

So here is the objective function (with two print diagnostics). I want to maximize it with respect to the argument lambda.s. (As a matter of interest, I am not maximizing a likelihood here. I am trying to optimize an importance sampler.)

log.pr.data<-function(lambda.s,n1,n0,lambda.star,psi0,tobs,g=T.chan){
           print("Function log.pr.data")
           print(g)
          psi.s<-boundary(lambda.s,g,psi0,tobs,n1,n0)
         -my.dbinom(n0*lambda.s,n0,lambda.star,log=TRUE)
}

I have no problems with the command:

nlm(log.pr.data,p=0.6,n1=n1,n0=n0,lambda.star=lambda.star,psi0=psi0,tobs=tobs)

It works fine. But I want to be able to change the function g=T.chan. So I redefined the function leaving g unspecified in log.pr.data. In other words, I just removed the "=T.chan" in the argument list. I checked that the function works OK. For instance with the command

 log.pr.data(l,n1,n0,lambda.star,psi0,tobs,T.chan)

for a range of values of "l" and it works fine and gives the same values as the previous function where g=T.chan is specified in the argument list. So the function T.chan is being passed properly it appears.

I then try to optimize

nlm(log.pr.data,p=0.6,n1=n1,n0=n0,lambda.star=lambda.star,psi0=psi0,tobs=tobs,g=T.chan)

and I get the error

Error in nlm(function(x) f(x, …), p,
hessian, typsize, fscale, msg, :
invalid NA value in parameter

It is also interesting that there does not seem to be a single call to log.pr.data because "Function log.pr.data" is not printed. In earlier attempts to troubleshoot this problem, I realized that I was using the symbol "f" for the function being passed and that this might cause problems because nlm called its objective function "f". So I changed it to "g" throughout.

Best Answer

First, I agree with Eduardo Leoni's comment that we need a reproducible example, so that we have “real” code to work with.

My blind guess would be that, because in R you can abbreviate parameters, g is not correctly resolved between “your” g and an abbreviated gradtol from the nlm function.

On the other hand, if I try your code fragments, nlm proceeds with calling log.pr.data and fails only at the second print statement because T.chan isn't known.

So sadly, without a working (i.e. failing reproducibly) example, it's difficult to find out what's wrong.

Related Topic