Hi all, I'm trying to make a little script to determine an "unknown" rate for a number of known exponential trials. My Code: #Set Trials and generate number trials=100 rand<-runif(1,0,1) vector=0 #Generate vector of 100 random exponentials and sum them for (i in 1:100) { vector<-rexp(trials,rate=rand) } sumvect=sum(vector) #Create the log likelihood function LL<-function(x) {(trials*log(x))-(x*sumvect)} optim(1,LL,method="BFGS") The "rand" variable should be between 0 and 1 and is what I am trying to approximate. However, as it is I generally get a value in the tens of thousands. I'm sure it's something simple but I can't find my error. Jon
You're minimizing the log likelihood, but you want to minimize the *negative* log likelihood. Also, optimize() is better than optim() if you have a function of only one argument. Replace Jon Moroney wrote:> > #Create the log likelihood function > LL<-function(x) {(trials*log(x))-(x*sumvect)} > > optim(1,LL,method="BFGS") >with LL<-function(x) {-trials*log(x)+x*sumvect} optimize(LL,c(0,1e5)) or better yet, to avoid errors and make generalizeable, do this LL<-function(x) {-sum(dexp(vector,x,log=TRUE))} optimize(LL,c(0,1e5)) -- View this message in context: http://n4.nabble.com/Trouble-with-optim-function-tp1559382p1560118.html Sent from the R help mailing list archive at Nabble.com.
optim really isn't intended for [1D] functions. And if you have a constrained search area, it pays to use it. The result you are getting is like the second root of a quadratic that you are not interested in. You may want to be rather careful about the problem to make sure you have the function you intend.> I'm trying to make a little script to determine an "unknown" rate for a > number of known exponential trials. > > > > My Code: > #Set Trials and generate number > trials=100 > rand<-runif(1,0,1) > vector=0 > > #Generate vector of 100 random exponentials and sum them > for (i in 1:100) { > vector<-rexp(trials,rate=rand) > } > sumvect=sum(vector) > > #Create the log likelihood function > LL<-function(x) {(trials*log(x))-(x*sumvect)} > > optim(1,LL,method="BFGS") > > > > The "rand" variable should be between 0 and 1 and is what I am trying to > approximate. However, as it is I generally get a value in the tens of > thousands. I'm sure it's something simple but I can't find my error.How about? > ans2<-optimize(f=LL,interval=c(0,1)) > ans2 $minimum [1] 6.610696e-05 $objective [1] -962.4322 > J Nash