# Re: [R] Simple question on a function

From: Christoph Buser <buser_at_stat.math.ethz.ch>
Date: Mon 02 Oct 2006 - 13:09:12 GMT

Dear Serguei

There might be more efficient ways, but this should work:

## Define function that you want to optimize. In your case I
## copied your code, but included freq as a second argument:
fun <- function(x, freq)
{

```  (freq-(1-x)*(1-x)-x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
(freq-(1-x)*x+x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
(freq-x*(1-x)+x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
(freq-x*x-x*sqrt(x*(1-x)*x*(1-x)))^2/freq
```
}

## Define mat with values for freq (your code)
mat<-matrix(c(0.4,0.1,0.1,0.4), byrow=TRUE, nrow=10, ncol=4)

## Use apply on mat

apply(mat, 1, function(freq, start) optim(start, fun, method="BFGS", freq = freq)\$par, start = c(0.1,0.1,0.1))

You still can use t() to transpose the matrix if you want the solutions by row instead of columns.

Please remark that in general optim returns a list, including several arguments, e.g. convergence that indicates if optim has converge.
Since you wanted a matrix I only returned optim(...)\$par. This might be dangerous since the additional information gets lost. Maybe it is better to save the output in a list. You can try:

apply(mat, 1, function(freq, start) optim(start, fun, method="BFGS", freq = freq), start = c(0.1,0.1,0.1))

to see the difference.

Hope this helps

Christoph

Christoph Buser <buser@stat.math.ethz.ch> Seminar fuer Statistik, LEO C13
```ETH Zurich	8092 Zurich	 SWITZERLAND
phone: x-41-44-632-4673		fax: 632-1228
```

http://stat.ethz.ch/~buser/

Serguei Kaniovski writes:

``` > I would like to apply the following function to the rows of the matrix
> "mat", so that freq,...,freq are the four elements of each row.
>
> min_chi2<-function(freq){
>
> obj<-function(x){
> (freq-(1-x)*(1-x)-x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
> (freq-(1-x)*x+x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
> (freq-x*(1-x)+x*sqrt(x*(1-x)*x*(1-x)))^2/freq+
> (freq-x*x-x*sqrt(x*(1-x)*x*(1-x)))^2/freq
> }
>
> optim(c(0.1,0.1,0.1),obj,NULL,method="BFGS")\$par
> }
>
> mat<-matrix(c(0.4,0.1,0.1,0.4), byrow=TRUE, nrow=10, ncol=4)
>
> Questions:
> 1. How to do this using the "apply" function?
> 2. Can "opmit" be used directly, i.e. without needing to define the
> function "min_chi2"?
> 3. How to pass the vector of initial conditions (c(0.1,0.1,0.1)) as an
> argument to "apply"?
>
> The output should be a 10x3 matrix containing 0.5 0.5 0.6 in each row.
>
> Thanks a lot,
> Serguei
> --
> ___________________________________________________________________
>
> Austrian Institute of Economic Research (WIFO)
>
> Name: Serguei Kaniovski			P.O.Box 91
> Tel.: +43-1-7982601-231			Arsenal Objekt 20
> Fax:  +43-1-7989386			1103 Vienna, Austria
> Mail: Serguei.Kaniovski@wifo.ac.at
>
> http://www.wifo.ac.at/Serguei.Kaniovski
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help