# NOT RUN {
# load entropy library
library("entropy")
# probabilities for two random variables
freqs1 = c(1/5, 1/5, 3/5)
freqs2 = c(1/10, 4/10, 1/2)
# KL divergence between x1 to x2
KL.plugin(freqs1, freqs2)
# and corresponding (half) chi-squared divergence
0.5*chi2.plugin(freqs1, freqs2)
## relationship to Pearson chi-squared statistic
# Pearson chi-squared statistic and p-value
n = 30 # sample size (observed counts)
chisq.test(n*freqs1, p = freqs2) # built-in function
# Pearson chi-squared statistic from Pearson divergence
pcs.stat = n*chi2.plugin(freqs1, freqs2) # note factor n
pcs.stat
# and p-value
df = length(freqs1)-1 # degrees of freedom
pcs.pval = 1-pchisq(pcs.stat, df)
pcs.pval
# }
Run the code above in your browser using DataLab