Example R programs and commands
24. Tests for serial randomness in time series
# All lines preceded by the "#" character are my comments.
# All other left-justified lines are my input.
# All other indented lines are the R program output.
# PARAMETRIC: test of serial randomness from differences.
# Generate a random time series
n <- 100 # length of the time series
x <- rnorm(n) # independent standard normals
dx <- x[2:n]-x[1:(n-1)] # dx[i] = x[i+1]-x[i], i=1,2,...,n-1
s2 <- var(x) # variance of x[]
s2star <- sum(dx^2)/(2*(n-1)) # variance of dx[]
C <- 1-s2star/s2; C # test statistic; critical values are in Table B.30
Z <- C*sqrt((n^2-1)/(n-2)) # normal approximation, valid for n>30
pnorm(Z, lower.tail=FALSE)
# Generate a nonrandom time series
n <- 100 # length of the time series
x <- (1:n)+rnorm(n) # independent standard normals with an increasing trend
dx <- x[2:n]-x[1:(n-1)] # dx[i] = x[i+1]-x[i], i=1,2,...,n-1
s2 <- var(x) # variance of x[]
s2star <- sum(dx^2)/(2*(n-1)) # variance of dx[]
C <- 1-s2star/s2; C # test statistic; critical values are in Table B.30
Z <- C*sqrt((n^2-1)/(n-2)) # normal approximation, valid for n>30
pnorm(Z, lower.tail=FALSE)
# NONPARAMETRIC: Runs test for two categories.
# Get the contributed R function runs.test() from the package tseries
# at
# http://cran.r-project.org/web/packages/tseries/index.html
#
# Unpack the archive, copy the file "test.R" it into your R folder and run
source("test.R")
# ...or else cut and paste the file into your R console.
# Generate a nonrandom time series of 13 selections from 2 categories:
x<-factor(c(1,1,1,1,1,1,1,1,1,2,2,2,2)); x
runs.test(x)
# Generate a random time series of 100 selections from 2 categories:
x <- factor(sign(rnorm(100))); x
runs.test(x)