Dear R users, I am trying to find the mle that involves integration. I am using the following code and get an error when I use the nlm function d<-matrix(c(1,1,0,0,0,0,0,0,2,1,0,0,1,1,0,1,2,2,1,0),nrow=10,ncol=2) h<-matrix(runif(20,0,1),10) integ<-matrix(c(0),nrow=10, ncol=2) ll<-function(p){ for (k in 1:2){ for(s in 1:10){ integrand<-function(x) x^d[s,k]*exp(-x*gamma(1+1/p))^p*p*x^(p-1)*exp(-x*h[s,k]) integ[s,k]<-integrate(integrand,0,Inf)$value } } lik<-colSums(integ) -lik } initial<-c(1) t<-nlm(ll,initial) Error in nlm(ll, initial) : invalid function value in 'nlm' optimizer Any suggestions will be greatly appreciated. Thank you in advance -- View this message in context: http://r.789695.n4.nabble.com/likelihood-function-involving-integration-error-in-nlm-tp4646697.html Sent from the R help mailing list archive at Nabble.com.
Berend Hasselman
2012-Oct-19 09:19 UTC
[R] likelihood function involving integration, error in nlm
On 19-10-2012, at 04:40, stats12 wrote:> Dear R users, > > I am trying to find the mle that involves integration. > > I am using the following code and get an error when I use the nlm function > > d<-matrix(c(1,1,0,0,0,0,0,0,2,1,0,0,1,1,0,1,2,2,1,0),nrow=10,ncol=2) > h<-matrix(runif(20,0,1),10) > > integ<-matrix(c(0),nrow=10, ncol=2) > ll<-function(p){ > for (k in 1:2){ > for(s in 1:10){ > integrand<-function(x) > x^d[s,k]*exp(-x*gamma(1+1/p))^p*p*x^(p-1)*exp(-x*h[s,k]) > integ[s,k]<-integrate(integrand,0,Inf)$value > } > } > lik<-colSums(integ) > -lik > } > initial<-c(1) > t<-nlm(ll,initial) > Error in nlm(ll, initial) : invalid function value in 'nlm' optimizerBefore the call of nlm you should insert ll(initial) to check. You'll see that your function returns a vector and not a scalar as it should. I guess that ll() should return sum(-lik) or better -sum(integ) Berend
Thanks for pointing that out. Made some modifications and it worked. -- View this message in context: http://r.789695.n4.nabble.com/likelihood-function-involving-integration-error-in-nlm-tp4646697p4646764.html Sent from the R help mailing list archive at Nabble.com.