Chi-squared goodness of fit test in R
Asked Answered
H

2

13

I have a vector of observed values and also a vector of values calculated with model:

actual <- c(1411,439,214,100,62,38,29,64)
expected <- c(1425.3,399.5,201.6,116.9,72.2,46.3,30.4,64.8)

Now I'm using the Chi-squared goodness of fit test to see how well my model performs. I wrote the following:

chisq.test(expected,actual) 

but it doesn't work. Can you help me with this?

Holiday answered 10/7, 2012 at 7:14 Comment(3)
it works for me, what error do you get?Cynde
it works for me too but the result is not correct. X-squared should be 10.2 with p-value= 0.07 but it gives me X-squared= 56 with p-value=.2289Holiday
Are you sure? Those numbers look pretty close together. How are you getting that chi-square value of 10.2 and that p-value of 0.07?Musso
A
15

X^2 = 10.2 at 7 degrees of freedom will give you a p ~ 0.18 .

> 1-pchisq(10.2, df = 7)
[1] 0.1775201

You should pass on the expected values under argument p. Make sure you scale your values to sum to 1.

> chisq.test(actual, p = expected/sum(expected))

    Chi-squared test for given probabilities

data:  actual 
X-squared = 10.2581, df = 7, p-value = 0.1744

This about what X^2 test is doing. You give the function a model (expected) and ask - how likely it is that my observed data came from a population that "generated" expected?

Anemograph answered 10/7, 2012 at 8:25 Comment(2)
In fact I have a model and I have extracted the "expected" values out of my model and now I need to see how close the 'actual' values and the values extracted from the model are.Holiday
If your expected values don't sum to 1, you can also add rescale.p=TRUE (so chisq.test(actual, p=expected, rescale.p=TRUE), then they’ll automatically be rescaled to sum to 1.Lowson
P
0

chisq.test(actual, p=expected, rescale.p = TRUE) does get the correct values as calculated "by hand" in Excel.

Pentheus answered 28/2, 2023 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.