[R] Extend my code to run several data at once.
EdBo
n.bowora at gmail.com
Sat Jul 23 14:37:36 CEST 2011
Hi
I have a code that calculate maximisation using optimx and it is working
just fine. I want to extend the code to run several colomns of R_j where j
runs from 1 to 200. If I am to run the code in its current state, it means I
will have to run it 200 times manually. May you help me adjust it to
accomodate several rows of R_j and print the 200 results.
***Please do not get intimidated by the maths in the code.***
my code
######
afull=read.table("D:/hope.txt",header=T)
library(optimx)
llik = function(x)
{
al_j=x[1]; au_j=x[2]; sigma_j=x[3]; b_j=x[4]
sum(na.rm=T,
ifelse(a$R_j< 0, log(1 / ( sqrt(2*pi) * sigma_j) )-
(1/( 2*sigma_j^2 ) ) * (
(a$R_j+al_j-b_j*a$R_m)^2 ) ,
ifelse(a$R_j>0 , log(1 / ( sqrt(2*pi) * sigma_j) )-
(1/( 2*sigma_j^2 ) ) * (
(a$R_j+al_j-b_j*a$R_m)^2 ) ,
log(ifelse (( pnorm (au_j, mean=b_j * a$R_m, sd= sqrt(sigma_j^2))-
pnorm(al_j, mean=b_j * a$R_m, sd=sqrt
(sigma_j^2)) ) > 0,
(pnorm (au_j,mean=b_j * a$R_m, sd= sqrt(sigma_j^2))-
pnorm(al_j, mean=b_j * a$R_m, sd= sqrt(sigma_j^2)
)),
1) ) ) )
)
}
start.par = c(-0.01,0.01,0.1,1)
#looping now
runs=133/20+1
out <- matrix(NA, nrow = runs, ncol = 4,
dimnames = list(paste("Qtr:", 1:runs , sep = ''),
c("al_j", "au_j", "sigma_j", "b_j")))
## Estimate parameters based on rows 0-20, 21-40, 41-60 of afull
for (i in 1:runs) {
index_start=20*(i-1)+1
index_end= 20*i
a=afull[index_start:index_end,]
out[i, ] <- optimx(llik,par = start.par,method = "Nelder-Mead",
control=list(maximize=TRUE) )[[1]][[1]]
}
## Yields
> out
al_j au_j sigma_j b_j
Qtr:1 0.0012402032 0.001082986 0.012889809 1.14095125
Qtr:2 0.0011302178 0.582718275 0.009376083 0.06615565
Qtr:3 0.0013349347 0.417495301 0.013286103 0.60548903
Qtr:4 -0.0016659441 0.162250321 0.015088915 0.67395511
Qtr:5 0.0043159984 0.004315976 0.013153039 1.17341907
Qtr:6 0.0027333033 0.527280348 0.018423347 0.53905153
Qtr:7 -0.0009214064 0.749695104 0.008730072 0.02108032
>
--
View this message in context: http://r.789695.n4.nabble.com/Extend-my-code-to-run-several-data-at-once-tp3688823p3688823.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list