EdBo wrote: > > Hi > > I have developed the code below. I am worried that the parameters I want > to be estimated are "not being found" when I ran my code. Is there a way I > can code them so that R recognize that they should be estimated. > > This is the error I am getting. > >> out1=optim(llik,par=start.par) > Error in pnorm(au_j, mean = b_j * R_m, sd = sigma_j) : > object 'au_j' not found > > #Yet al_j,au_j,sigma_j and b_j are just estimates that balance the > likelihood function? > > llik=function(R_j,R_m) > if(R_j< 0) > { > sum[log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+al_j-b_j*R_m))^2] > }else if(R_j>0) > { > sum[log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+au_j-b_j*R_m))^2] > }else if(R_j==0) > { > sum(log(pnorm(au_j,mean=b_j*R_m,sd=sigma_j)-pnorm(al_j,mean=b_j*R_m,sd=sigma_j))) > } > start.par=c(al_j=0,au_j=0,sigma_j=0.01,b_j=1) > out1=optim(par=start.par,llik) > > My Data > > R_j R_m > 2e-03 0.026567295 > 3e-03 0.009798475 > 5e-02 0.008497274 > -1e-02 0.012464578 > -9e-04 0.002896023 > 9e-02 0.000879473 > 1e-02 0.003194435 > 6e-04 0.010281122 >
You are only passing the R_j and R_m data as argument to your function. The parameters that are to be used for the maximization must also be passed as arguments. This is clearly explained in the help page for optim. So your function should read llik <- function(par, R_j, R_m) { al_j <- par[1] au_j <- par[2] sigma_j <- par[3] b_j <- par[4] if(R_j< 0) { sum(log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+al_j-b_j*R_m))^2) } else if(R_j>0) { sum(log(1/(2*pi*(sigma_j^2)))-(1/(2*(sigma_j^2))*(R_j+au_j-b_j*R_m))^2) } else if(R_j==0) { sum(log(pnorm(au_j,mean=b_j*R_m,sd=sigma_j)-pnorm(al_j,mean=b_j*R_m,sd=sigma_j))) } } And then use optim as follows: out1 <- optim(par=start.par,llik, R_j=R_j, R_m=R_m) But this is not going to work as you want it to. You'll get warnings: 1: In if (R_j < 0) { ... : the condition has length > 1 and only the first element will be used R_j is a vector and if() takes a scalar (or vector of length 1). So it is not at all clear what the purpose of the if statement is. Berend -- View this message in context: http://r.789695.n4.nabble.com/Hint-improve-my-code-tp3641354p3641520.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.