How to perform chi square test for goodness of fit in R?


The chi square test for goodness of fit is a nonparametric test to test whether the observed values that falls into two or more categories follows a particular distribution of not. We can say that it compares the observed proportions with the expected chances. In R, we can perform this test by using chisq.test function. Check out the below examples to understand how it is done.

Example1

Live Demo

> x1<-sample(0:9,200,replace=TRUE)
> x1

Output

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

Example

> x1_table<-table(x1)
> x1_table

Output

x1
0 1 2 3 4 5 6 7 8 9
24 23 14 18 23 21 21 17 24 15
> chisq.test(x1_table,p=rep(0.1,10))

Chi-squared test for given probabilities

data: x1_table
X-squared = 6.3, df = 9, p-value = 0.7096

Example2

Live Demo

> x2<-c(14,25,17,14)
> p<-c(0.25,0.25,0.25,0.25)
> chisq.test(x2,p=p)

Output

Chi-squared test for given probabilities

data: x2
X-squared = 4.6286, df = 3, p-value = 0.2011

Example3

Live Demo

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

Output

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

Example

> x3_table<-table(x3)
> x3_table

Output

x3
0 1 2 3 4 5 6 7 8 9 10
2 5 20 29 33 37 30 23 10 8 3
> chisq.test(x3_table,p=rep(1/11,11))

Chi-squared test for given probabilities

data: x3_table
X-squared = 93.15, df = 10, p-value = 1.268e-15

Example4

Live Demo

> x4<-c(24,98,30,35,27,28)
> chisq.test(x4)

Output

Chi-squared test for given probabilities

data: x4
X-squared = 100.6, df = 5, p-value < 2.2e-16

Example5

Live Demo

> x5<-c(12,15,17,15,9,14)
> p<-c(0.1,0.1,0.2,0.2,0.1,0.1)
> chisq.test(x5,p)

Output

Pearson's Chi-squared test

data: x5 and p
X-squared = 3.75, df = 4, p-value = 0.4409

Warning message:
In chisq.test(x5, p) : Chi-squared approximation may be incorrect

Example6

Live Demo

> x6<-c(36,27,25,84,14,25,36,27,29)
> chisq.test(x6,p=rep(1/9,9))

Output

Chi-squared test for given probabilities

data: x6
X-squared = 94.812, df = 8, p-value < 2.2e-16

Updated on: 21-Nov-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements