[R] R: Help; error in optim
Berend Hasselman
bhh at xs4all.nl
Mon Apr 16 07:47:43 CEST 2012
On 16-04-2012, at 07:04, Christopher Kelvin wrote:
> Hello,
> When i run the code below from Weibull distribution with 30% censoring by using optim i get an error form R, which states that
>
>
> Error in optim(start, fn = z, data = q, hessian = T) :
> objective function in optim evaluates to length 25 not 1
>
> can somebody help me remove this error. Is my censoring approach correct.
>
> n=25;rr=1000
> p=1.5;b=1.2
> for (i in 1:rr){
> q<-c(t,cen)
> t<-rweibull(25,shape=p,scale=b)
> meantrue<-gamma(1+(1/p))*b
> meantrue
> d<-meantrue/0.30
> cen<- runif(25,min=0,max=d)
> cen
> s<-ifelse(t<=cen,1,0)
>
> z<-function(data,p){
> beta<-p[1]
> eta<-p[2]
> log1<-(n*cen*log(p[1])-n*cen*(p[1])*log(p[2])+cen*(p[1]-1)*sum(log(t))-n*sum((t/(p[2]))^(p[1])))
> return(-log1)
> }
> start <-c(0.5,0.5)
> zz<-optim(start,fn=z,data=q,hessian=T)
>
> m1<-zz$par[2]
> p<-zz$par[1]
>
> }
> m1
> p
The example as given doesn't run.
The first assignment after the start of the for loop ( q <- ...) gives an error message: object 'cen' not found.
The assignment needs to moved to after the line with ifelse.
In function z object 'cen' (with length 25) is used in the calculation of log1, which becomes a vector of length 25.
You need to review the definition of log1 in function z.
Finally: why are you assigning p[1] and p[2] to beta and eta and nor using these variables?
Berend
More information about the R-help
mailing list