Kruskal-Wallis 検定とは、まあ、一元配置分散分析のノンパラメトリック版とお考え下さい。 分散分析と違い、「順序」以上の尺度水準で利用が可能で、また当然ながら正規分布等も仮定しておりませんので、利用範囲のとても広い検定法だと思います。
# Kruskal-Wallis test
# (C) Copyright 2002, Hisashi SATO
def KW_test(array)
# 諸準備
rank = Array.new() # 各sampleの順序の記録用行列
sample_size = 0.0 # 全サンプル数
for block in 0..array.size-1
rank << Array.new(array[block].size , 0.0)
sample_size += array[block].size
end
# 各サンプルの順位、各ブロックの順序合計、各順序の重複数を算出
sum_of_rank = Array.new(array.size, 0.0) # 各blockの順序合計の記録用行列
tie = Hash.new # 各順序の重複数の記録用Hash
for block1 in 0..array.size-1
count4 = 0.0
for n1 in 0..array[block1].size-1
count1, count2, count3 = 0.0, 0.0, 0.0
for block2 in 0..array.size-1
for n2 in 0..array[block2].size-1
if array[block1][n1] > array[block2][n2] then count1 += 1
elsif array[block1][n1] == array[block2][n2] then count2 += 1
end
end
end
for i in count1+1..(count1 + count2)
count3 += i
end
rank[block1][n1] = count3 / count2 # sample毎に順序を記録
tie[count3 / count2] = count2 # 順序値毎に重複数を記録
count4 += count3 / count2
end
sum_of_rank[block1] = count4 # block毎に順序合計を記録
end
# 検定統計量hと重複順位補正項dの算出
h, d, count5, count6 = 0.0, 0.0, 0.0, 0.0
for block in 0..array.size-1
count5 += (sum_of_rank[block]**2) / array[block].size
end
h = ( 12/( sample_size*(sample_size+1) ) ) * count5 - 3*(sample_size+1)
tie = tie.values
tie.delete(1.0)
tie.each{|i| count6 += i**3 - i }
d = 1 - count6 / ( sample_size**3 - sample_size )
return h, d
end