ご存じのこととは思いますが,念の為
Julia で 2 変数間のスピアマンの順位相関係数を求めるには,
using StatsBase, Statistics
corspearman([1,2,3,4,5], [3,2,1,2,3])
です。
スピアマンの順位相関係数行列を求めるとき,
function spearmancor0(x::Array{Float64,2})
nc = size(x, 2)
r = ones(nc, nc)
for i = 2:nc
for j = 1:i
r[i, j] = r[j, i] = corspearman(x[:, i], x[:, j])
end
end
return r
end
としてはいけません。
corspearman は データ行列も受け付けます。
以下のように定義した関数がやるように,データ行列を列ごとに平均順位を付け,そのあとで cor 関数を呼びます。
function spearmancor(x::Array{Float64,2})
rank = similar(x, Float64)
for i = 1:size(x, 2)
rank[:, i] = tiedrank(x[:, i])
end
return cor(rank)
end
のようにしましょう。
時間計測すると,以下のようになります。
x = randn(10000, 100);
@time b = spearmancor0(x); # 8.367428 seconds (70.69 k allocations: 2.260 GiB, ...
@time a = spearmancor(x); # 0.097368 seconds (714 allocations: 38.250 MiB, ...
@time c = corspearman(x); # 0.094456 seconds (1.06 k allocations: 38.337 MiB
a == b # true
a == c # true
90 倍ほど速いです。当然ですが,得られる相関係数行列は同じです。
※コメント投稿者のブログIDはブログ作成者のみに通知されます