Damokun wrote: > > Dear all, > > I am trying to optimize a logistic function using optim, inside the > following functions: > #Estimating a and b from thetas and outcomes by ML > > IRT.estimate.abFromThetaX <- function(t, X, inits, lw=c(-Inf,-Inf), > up=rep(Inf,2)){ > optRes <- optim(inits, method="L-BFGS-B", fn=IRT.llZetaLambdaCorrNan, > gr=IRT.gradZL, > lower=lw, upper=up, t=t, X=X) > c(optRes$par[2], -(optRes$par[1]/optRes$par[2]) ) > } > > #Estimating a and b from thetas and outcomes by ML, avoiding 0*log(0) > IRT.estimate.abFromThetaX2 <- function(tar, Xes, inits, lw=c(-Inf,-Inf), > up=rep(Inf,2)){ > > optRes <- optim(inits, method="L-BFGS-B", fn=IRT.llZetaLambdaCorrNan, > gr=IRT.gradZL, > lower=lw, upper=up, t=tar, X=Xes) > c(optRes$par[2], -(optRes$par[1]/optRes$par[2]) ) > } > > The problem is that this does not work: >> IRT.estimate.abFromThetaX(sx, st, c(0,0)) > Error in optim(inits, method = "L-BFGS-B", fn = IRT.llZetaLambdaCorrNan, > : > L-BFGS-B needs finite values of 'fn' > But If I try the same optim call on the command line, with the same data, > it works fine: >> optRes <- optim(c(0,0), method="L-BFGS-B", fn=IRT.llZetaLambdaCorrNan, > + gr=IRT.gradZL, > + lower=c(-Inf, -Inf), upper=c(Inf, Inf), t=st, X=sx) >> optRes > $par > [1] -0.6975157 0.7944972 > $convergence > [1] 0 > $message > [1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH" >
In your command line you have set t=st and X=sx. However in the alternative you do: IRT.estimate.abFromThetaX(sx, st, c(0,0)) Therefore you are assigning sx to t and st to X in the IRT.estimate.abFromThetaX function, which is reversed from your command line call. You should switch sx and st in the function call: IRT.estimate.abFromThetaX(st, sx, c(0,0)) and then all will be well. best Berend If yoou -- View this message in context: http://r.789695.n4.nabble.com/optim-works-on-command-line-but-not-inside-a-function-tp3025414p3026099.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@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.