#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。
Python による統計処理
http://aoki2.si.gunma-u.ac.jp/Python/PythonDir.tar.gz
Bhapkar 検定と一般化マクネマー検定
http://aoki2.si.gunma-u.ac.jp/Python/Bhapkar_test.pdf
ファイル名: bhapkartest.jl 関数名: bhapkartest
翻訳するときに書いたメモ
==========#
using Rmath
function bhapkartest(tbl)
r, c = size(tbl)
r == c || error("'tbl' != a square matix.'")
r1 = r - 1
N = sum(tbl)
pi = tbl ./ N
picolSums = vec(sum(pi, dims=1)) # π(+, t)
pirowSums = sum(pi, dims=2) # π(s, +)
d = (picolSums .- pirowSums)[1:r1]
V0 = zeros(r1, r1)
V1 = zeros(r1, r1)
for s = 1:r1
for t = 1:r1
if s == t
V0[s, s] = pirowSums[s] + picolSums[s] - 2 * pi[s, s]
V1[s, s] = V0[s, s] - (pirowSums[s] - picolSums[s])^2
else
V0[s, t] = -pi[s, t] - pi[t, s]
V1[s, t] = V0[s, t] - (picolSums[s] - pirowSums[s]) * (picolSums[t] - pirowSums[t])
end
end
end
Z0 = N * d' * inv(V0) * d
p0 = pchisq(Z0, r1, false)
Z1 = N * d' * inv(V1) * d
p1 = pchisq(Z1, r1, false)
println("Generalized McNemar test (Stuart-Maxwell test)")
println("chisq. = $Z0, df = $r1, p value = $p0")
println("Bhapkar's test")
println("chisq. = $Z1, df = $r1, p value = $p1")
Dict(:Z0 => Z0, :Z1 => Z1, :df => r1, :p0 => p0, :p1 => p1)
end
tbl = [1520 266 124 66
234 1512 432 78
117 362 1772 205
36 82 179 492]
a = bhapkartest(tbl)
# Generalized McNemar test (Stuart-Maxwell test)
# chisq. = 11.956569622982544, df = 3, p value = 0.007533425054800585
# Bhapkar's test
# chisq. = 11.97572015552566, df = 3, p value = 0.007466797469724006