[R] Simple question on a function

Serguei Kaniovski kaniovsk at wifo.ac.at
Mon Oct 2 11:53:49 CEST 2006


I would like to apply the following function to the rows of the matrix 
"mat", so that freq[1],...,freq[4] are the four elements of each row.

min_chi2<-function(freq){

obj<-function(x){
(freq[1]-(1-x[1])*(1-x[2])-x[3]*sqrt(x[1]*(1-x[1])*x[2]*(1-x[2])))^2/freq[1]+
(freq[2]-(1-x[1])*x[2]+x[3]*sqrt(x[1]*(1-x[1])*x[2]*(1-x[2])))^2/freq[2]+
(freq[3]-x[1]*(1-x[2])+x[3]*sqrt(x[1]*(1-x[1])*x[2]*(1-x[2])))^2/freq[3]+
(freq[4]-x[1]*x[2]-x[3]*sqrt(x[1]*(1-x[1])*x[2]*(1-x[2])))^2/freq[4]
}

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 at wifo.ac.at

http://www.wifo.ac.at/Serguei.Kaniovski



More information about the R-help mailing list