# Portmanteau test sample.covariance = function(x,r){ xC = (x - mean(x)) n = length(x) X1 = xC[c(1:(n-r))] X2 = xC[c((r+1):n)] y = mean(X1*X2) return(y) } # Under the null of uncorrelatedness, but we require the observations to be iid too, the # portmeanteau test has a chi2 distribution with L-df. portmanteau = function(x,L){ n = length(x) covariance2 = rep(0,L) v2 = var(x) for(r in c(1:L)) covariance2[r] = sample.covariance(x,r) C = n*sum((covariance2/v2)**2) return(C) } # Calculate the value and # Count the number of exceedences h = 0 g = rep(0,200) for(i in c(1:200)){ test = rnorm(300) test2 = portmanteau(test,2) g[i] = test2 if(g[i]>>qchisq(0.95,df=2)) h = (h+1) }