# How to identify the difference between Kolmogorov Smirnov test and Chi Square Goodness of fit test in R?

R ProgrammingServer Side ProgrammingProgramming

The Chi Square Goodness of fit test is used to test whether the distribution of nominal variables is same or not as well as for other distribution matches and on the other hand the Kolmogorov Smirnov test is only used to test to the goodness of fit for a continuous data. The difference is not about the programming tool, it is a concept of statistics.

## Example

Live Demo

> x<-rnorm(20)
> x

## Output

[1] 0.078716115 -0.682154062 0.655436957 -1.169616157 -0.688543382
[6] 0.646087104 0.472429834 2.277750805 0.963105637 0.414918478
[11] 0.575005958 -1.286604138 -1.026756390 2.692769261 -0.835433410
[16] 0.007544065 0.925296720 1.058978610 0.906392907 0.973050503

## Example

> ks.test(x,pnorm)

One-sample Kolmogorov-Smirnov test

data: x
D = 0.2609, p-value = 0.1089
alternative hypothesis: two-sided

Chi-Square test:

> chisq.test(x,p=rep(1/20,20))
Error in chisq.test(x, p = rep(1/20, 20)) :
all entries of 'x' must be nonnegative and finite

With discrete distribution −

## Example

Live Demo

> y<-rpois(200,5)
> y

## Output

[1] 6 8 7 3 5 7 6 5 2 6 4 4 3 6 6 6 6 11 7 5 4 8 6 1 3
[26] 10 4 4 9 5 2 6 4 1 5 4 4 5 1 7 8 7 3 6 6 6 2 8 7 6
[51] 7 5 5 4 6 5 3 5 3 4 4 9 3 3 3 8 3 3 2 5 4 6 6 8 4
[76] 6 12 6 1 5 5 5 0 7 4 7 7 3 2 5 5 2 5 5 4 6 4 3 4 4
[101] 4 6 5 1 2 4 4 4 8 5 8 6 3 4 5 2 3 3 3 6 7 4 4 5 3
[126] 5 5 5 8 2 5 8 1 2 3 5 9 4 3 5 6 3 6 3 6 3 7 4 4 1
[151] 3 5 0 7 2 9 6 10 2 6 4 5 1 7 2 8 7 4 2 5 4 2 4 5 6
[176] 3 9 3 9 5 9 7 3 1 3 9 5 6 3 10 7 5 5 6 7 4 2 5 5 1

## Example

> chisq.test(y,p=rep(1/200,200))

Chi-squared test for given probabilities

data: y
X-squared = 203.61, df = 199, p-value = 0.3964

Warning message:
In chisq.test(y, p = rep(1/200, 200)) :
Chi-squared approximation may be incorrect

## Example

Live Demo

> a<-sample(0:9,100,replace=TRUE)
> a

## Output

[1] 4 6 1 8 1 7 3 9 8 5 4 0 7 2 2 4 6 2 1 2 1 9 1 3 1 9 2 9 1 8 4 0 4 7 1 7 1
[38] 0 1 5 9 6 5 4 6 6 9 6 1 0 8 9 4 8 2 8 1 6 9 1 0 4 6 8 8 1 1 0 3 2 6 7 2 1
[75] 7 9 9 8 2 6 4 7 3 4 0 9 5 5 9 4 5 7 8 7 3 0 1 4 8 5

## Example

> ks.test(a,pnorm)

One-sample Kolmogorov-Smirnov test

data: a
D = 0.76134, p-value < 2.2e-16
alternative hypothesis: two-sided

Warning message:
In ks.test(a, pnorm) :
ties should not be present for the Kolmogorov-Smirnov test
> chisq.test(a,p=rep(1/100,100))

Chi-squared test for given probabilities

data: a
X-squared = 198.88, df = 99, p-value = 1.096e-08

Warning message:
In chisq.test(a, p = rep(1/100, 100)) :
Chi-squared approximation may be incorrect
Published on 04-Jan-2021 06:47:07