An example of an AR(1) simulation (D3) We'll do a "baby" simulation that illustrates functions and for-loop. Our first version will have some bad features (e.g. "embedded constants") =================================================== Suppose we want an AR(1) with model parameters rho=.4 and sigma=.2 Lets generate 100 of these First set up the vector to hold the values y<-rep(0,100) Now generate the first value according to the stationary distribution s<-sqrt(.04/.84) y[1]<-rnorm(1,sd=s) Now a for-loop for the rest for (i in 2:100){ y[i]<-0.4*y[i-1]+rnorm(1, sd=.2) } Look at y using plot and qqnorm. ================================================ Wrap this in a "hard wired" function SimAR<-function(n){ y<-rep(0,n) s=sqrt(.04/.84) y[1]<-rnorm(1,sd=s) for (i in 2:n){ y[i]<-0.4*y[i-1]+rnorm(1, sd=.2)} return(y) } Test this with n=10, n=100, etc. look at some of the results via plots. ============================================= How can you make the function better? Suppose you pass more than one argument to the function f --- that is, don't hard wire the constants in the way we did. This would make your function much more useful. Note: When developing functions you usually want to keep the function you are designing in a text file and then just cut and past the versions of your function into the command window of S-Plus.