# Test for uniformity in R

i am searching for a test for uniformity in R.

ks.test(x,'punif') looks quite good, but my data has only 6 different values (results of rolling a die) which leads to a lot of ties in the Kolmogorov-Smirnov test. I read that i only can ignore this if the number of ties is small in comparison to the whole sample.

Is there a better test?

• Consider looking at this answer by Ilmari Karonen: rpg.stackexchange.com/questions/70802/… He does not appear to present R code, but you can try to implement his suggestions in R and edit your question with your own R code if you have trouble. – Mark Miller Jan 6 '17 at 12:08
• thank you! Just to make sure i am right: pchisq(sum(((table(X)-N/6)^2)/N*6),5) where X is a vector of dice results and N is the length of the vector – zugabe Jan 6 '17 at 13:35
• I do not really have time now to check whether you have done it correctly. I suggest looking for a worked example either on the internet or in a textbook and comparing the answer your code gives with the known correct answer provided in the worked example. Probably search for 'fair die' test example, etc. If you cannot get the correct answer then post your code above in your question along with the correct answer. – Mark Miller Jan 6 '17 at 13:47
• Here is R code to test whether a die is fair: math.stackexchange.com/questions/1578932/… – Mark Miller Jan 6 '17 at 14:29
• The chi-square test immediately comes to mind. It will be applicable and easy to compute whenever you have more than 30 observations (that is, an expectation of five or more observations per possible value). For smaller numbers it's wise to simulate the sampling distribution of this statistic. – whuber Oct 8 '18 at 15:13

Per whuber's comment, the standard way to test for a particular discrete distribution (e.g., a uniform one - but also any other one) is the Pearson chi squared test. In R, use chisq.test(). A simulation:

> set.seed(1)
> rolls <- sample(1:6,10,replace=TRUE)
> chisq.test(rbind(table(factor(rolls,levels=1:6)),rep(length(rolls),6)/6))

Pearson's Chi-squared test

data:  rbind(table(factor(rolls, levels = 1:6)), rep(length(rolls),     6)/6)
X-squared = 0.94156, df = 5, p-value = 0.9671


You will get a warning that the p value may be incorrect because we have a small sample size (as a rule of thumb, the approximation used here works if each number is expected to come up at least five times). In such a case, you can instead use a simulation for the distribution of the test statistic under the null hypothesis. Just use simulate.p.value=TRUE (and possibly increase the number of Monte Carlo draws from the default of 2,000 using the B parameter).