###---------------------------------------------------------------------------- ### Runs test ###---------------------------------------------------------------------------- n <- 20 ## Let's assume "uHat" is the residual vector we have from the model. uHat <- runif(n, -1, 1) runstest <- as.numeric(uHat>0) N1 <- sum(runstest) # No. of positive residuals N2 <- n-N1 # No. of negative residuals ## No. of runs R <- 1 # Set initial Runs as one for(i in 2:n) { if(runstest[i] != runstest[i-1]) { R <- R+1 } } ## The no. of runs is normally distributed with mean and variance mean <- 2*N1*N2/n +1 variance <- 2*N1*N2*(2*N1*N2-n)/(n^2*(n+1)) ## The p-value ## Should be two sided test, i.e. the number of runs should not either to ## small or too big. pvalue <- pnorm(q = R, mean = mean, sd = sqrt(variance), lower.tail = FALSE)/2 ## or ## pvalue <- (1- pnorm(q = R, mean = mean, sd = sqrt(variance)))/2 ###---------------------------------------------------------------------------- ### Durbin - Watson d test ###---------------------------------------------------------------------------- uHat_t <- uHat[1:(n-1)] uHat_t1 <-uHat[2:n] d <- sum((uHat_t - uHat_t1)^2)/sum(uHat^2) ###---------------------------------------------------------------------------- ### The Breusch-Godfrey test ###---------------------------------------------------------------------------- ## Take home exercise