#RProject8_2_ks_test.r
set.seed(0)

par(mfcol=c(2,2))

#   2x2 Panel of Plots

#  Generate random sample from N(0,1) distribution
# 
x=rnorm(50)

# 1.1 Index plot of sample
plot(x)

# 1.2 Normal QQ Plot of sample
qqnorm(x)

# 1.3 Empirical CDF of sample

plot.ecdf(x)

# 1.4 Theoretical and empirical CDF together
par(mfcol=c(1,1))

x=rt(50,df=15)
plot.ecdf(x) 

x.grid=seq(-3,3,.001)
x.grid.pnorm<-pnorm(x.grid)
lines(x.grid,x.grid.pnorm,col='green',type="l")

# Compute Kolmogorov Smirnov Test Statistic
x.ecdf<-ecdf(x)
x.ecdf(x)
##  [1] 0.80 0.84 0.74 0.52 0.58 0.68 0.06 0.76 0.66 0.28 0.16 0.34 0.70 0.92
## [15] 0.48 0.78 0.44 0.82 0.64 0.96 0.02 0.90 0.22 0.72 0.18 0.42 0.32 1.00
## [29] 0.94 0.46 0.50 0.12 0.54 0.56 0.62 0.36 0.24 0.14 0.30 0.88 0.40 0.08
## [43] 0.38 0.20 0.04 0.10 0.26 0.60 0.86 0.98
KSstat=max(abs(x.ecdf(x)-pnorm(x)))
x.KSstat=x[KSstat==abs(x.ecdf(x)-pnorm(x))]
abline(v=x.KSstat, col='gray')
title(paste("KS-stat = ",as.character(round(KSstat,digits=3)),sep=""),adj=1)

# 2.  Apply R function ks.test() to sample
ks.test(x, y="pnorm")
## 
##  One-sample Kolmogorov-Smirnov test
## 
## data:  x
## D = 0.19902, p-value = 0.03273
## alternative hypothesis: two-sided