算額あれこれ

算額問題をコンピュータで解きます

Julia に翻訳--211 分布の差の検定,独立性の検定,K×M 分割表,2×2 分割表

#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。

分布の差の検定(独立性の検定)
http://aoki2.si.gunma-u.ac.jp/lecture/Cross/differenceofdist-r.html

独立性の検定(K×M 分割表)
http://aoki2.si.gunma-u.ac.jp/lecture/Cross/cross-r.html

独立性の検定(2×2 分割表)
http://aoki2.si.gunma-u.ac.jp/lecture/Cross/cross-r2.html

ファイル名: chisqtest2.jl  関数名: chisqtest2

翻訳するときに書いたメモ

==========#

using Rmath, Printf

function chisqtest2(x; correction=true)
    n, m = size(x)
    rowsum = sum(x, dims=2)
    colsum = sum(x, dims=1)
    expectation =  (rowsum * colsum) ./ sum(x)
    if sum(expectation .< 1) >= 1 ||sum(expectation .< 5) >= 0.2n*m
        println("Warning message: Chi-squared approximation may be incorrect")
    end
    difference = abs.(x - expectation)
    yates = 0
    correction && n == 2 && m == 2 && (yates = min(0.5, minimum(difference)))
    chisq = sum( ( (difference .- yates) .^ 2) ./ expectation)
    df =(n - 1) * (m - 1)
    pvalue = pchisq(chisq, df, false)
    @printf("chisq = %.5f,  df = %d,  p value = %.5f", chisq, df, pvalue)
end

x = [20 15 16 4
     15  7  9 4];

chisqtest2(x)
# Warning message: Chi-squared approximation may be incorrect
# chisq = 1.19810,  df = 3,  p value = 0.75346

x = [4 2
     1 6];

chisqtest2(x, correction=false)
# Warning message: Chi-squared approximation may be incorrect
# chisq = 3.74524,  df = 1,  p value = 0.05296

chisqtest2(x)
# Warning message: Chi-squared approximation may be incorrect
# chisq = 1.85908,  df = 1,  p value = 0.17273