# Now that was an embarassment, loops are very inefficient

October 25, 2012 Leave a comment

R’s learning curve can be very steep, and thankfully I am surrounded by intelligent and smart colleagues. The point is that the loop script in the last post is embarrassingly inefficient, and will work horribly if one intends to simulate a large sample.

Here’s a much more elegant solution, for 3.1 of EMT,but this time using the function argument in R.The script is provided by Evan Jo.

ARsample<-function(beta1=1,beta2=.8,n=25,y0=0){

y<-vector(length=n+1);y[1]<-y0

for (i in 2:n+1){

y[i]<-beta1+beta2*y[i-1]+rnorm(1)}

m<-embed(y,2);return(data.frame(y=m[,1],y1=m[,2]))};

meanbeta<-function(samplesize=25,n=100){

m<-data.frame(beta1=NA,beta2=NA);

for(i in 1:n){m[i,]<-coef(lm(y~y1,data=ARsample(n=samplesize)))}

return(colMeans(m));}

In particular look at how efficient this script is compared to the previous one.

And finally, this is why the honours stream is so much more intellectually rewarding to be in.

PS: Don’t worry, I will still be writing about economics, and hopefully when Quantdary takes off we’ll start having more interesting economics/finance related posts.