[R] Optim Problem

Berend Hasselman bhh at xs4all.nl
Tue Aug 28 06:14:57 CEST 2012


On 28-08-2012, at 03:12, Christopher Kelvin wrote:

> Hello,
> I want to estimate the exponential parameter by using optim with the following input, where t contains 40% of the data and q contains 60% of the data within an interval. In implementing the code command for optim i want it to contain both the t and q data so i can obtain the correct estimate. Is there any suggestion as to how this can be done. I have tried h<-c(t,q) but it is not working because q lies within an interval.
> 
> rate<-15;n<-100;a<-40;b<-60;rr<-1000
> ms11=ms22=0
> bia11=bia22=0
> t<-rexp(a,rate)
> for(i in 1:rr){
> C1<-runif(b,0,rate)
> C2<-rexp(b,rate)
> f2 <- function(C1, C2) {
>   r <- pmax(C1 , C2 + C1)
>   cbind(C1, r)
> } 
> m<-f2(C1,C2)
> x[1:b]<-(m[,1])
> u<-x[1:b]
> x[1:b]<-(m[,2])
> v<-x[1:b]
> q<-cbind(u,v)
> 
> h<-c(t,q)
> 
> z<-function(data ){ 
> rate<-p[2]
> log1<--(n/log(p[2]))-sum(t/(p[2]))+sum(log(exp(-(u/(p[2])))-exp(-(v/(p[2])))))
> return(-log1)
> }
> }
> start <- c(1,1)
> zz<-optim(start,fn=z,data=h,hessian=T)
> m1<-zz$par[2]

Running the code as given gives an error message 

Error in x[1:b] <- (m[, 1]) : object 'x' not found

So insert

x <- numeric(b) 

just before the for(i in 1:rr)

gives an error message

Error in fn(par, ...) : unused argument(s) (par)
Calls: optim -> <Anonymous> -> fn

Not surprising since the argument list of function z should have the parameter vector that optim is supposed to optimize as first argument.
So change the definition to

z<-function(p,data ){ 
rate<-p[2]
log1<--(n/log(p[2]))-sum(t/(p[2]))+sum(log(exp(-(u/(p[2])))-exp(-(v/(p[2])))))
return(-log1)
}

and this give the error message

Error in optim(start, fn = z, data = h, hessian = T) : 
  function cannot be evaluated at initial parameters

So I give up.
Please fix the example to at least something that is without these errors.

Berend




More information about the R-help mailing list