# Re: [R] Optim: Function definition

From: Spencer Graves <spencer.graves_at_pdf.com>
Date: Sat 14 Oct 2006 - 21:58:44 GMT

Have you tried making contour plots of your objective function, e.g., using expand.grid and 'contour' or 'contourplot', as described in Venables and Ripley (2002) Modern Applied Statistics with S (Springer)?

```      Hope this helps.
Spencer Graves

```

Serguei Kaniovski wrote:
> Hi all,
>
> I apply "optim" to the function "obj", which minimizes the goodness of
> fit statistic and obtains Pearson minimum chi-squared estimate for x,
> x and x. The vector "fr" contains the four observed frequencies.
>
> Since "fr[i]" appears in the denominator, I would like to substitute "0"
> in the sum if fr[i]=0.
>
> I tried an "ifelse" condition which works, but in some cases the
> solution seems rather odd. Is there anything wrong with the way second
> objective function is coded?
>
> obj<-function(x){
> (fr-x*x-x*sqrt(x*(1-x)*x*(1-x)))^2/fr+
> (fr-(1-x)*x+x*sqrt(x*(1-x)*x*(1-x)))^2/fr+
> (fr-x*(1-x)+x*sqrt(x*(1-x)*x*(1-x)))^2/fr+
> (fr-(1-x)*(1-x)-x*sqrt(x*(1-x)*x*(1-x)))^2/fr
> }
>
> obj<-function(x){
> ifelse(fr==0,0,(fr-x*x-x*sqrt(x*(1-x)*x*(1-x)))^2/fr)+
> ifelse(fr==0,0,(fr-(1-x)*x+x*sqrt(x*(1-x)*x*(1-x)))^2/fr)+
> ifelse(fr==0,0,(fr-x*(1-x)+x*sqrt(x*(1-x)*x*(1-x)))^2/fr)+
> ifelse(fr==0,0,(fr-(1-x)*(1-x)-x*sqrt(x*(1-x)*x*(1-x)))^2/fr)

> }
>
> sval=rep(0.1,3)
> fr<-c(0,0.1,0.2,0.3)
>
> optim(sval,obj, method="BFGS")\$par
>
> Thank you,
> Serguei
>

R-help@stat.math.ethz.ch 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. Received on Sun Oct 15 08:04:46 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sat 14 Oct 2006 - 22:30:10 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.