#==========
Julia の修行をするときに,いろいろなプログラムを書き換えるのは有効な方法だ。
以下のプログラムを Julia に翻訳してみる。
Reduced Major Axis regression
http://aoki2.si.gunma-u.ac.jp/R/RMA.html
ファイル名: rma.jl 関数名: rma
翻訳するときに書いたメモ
もはや,特になし。
==========#
using Statistics, Distributions, Printf, Plots
function rma(x, y; sig=0.95, col1=:black, col2=:red, xlab="", ylab="",
legend=:best)
# legend :right, :left, :top, :bottom, :inside, :best, :legend,
# :topright, :topleft, :bottomleft, :bottomright
n = length(x)
n1 = n-1
df = n-2
slope = sign(cor(x, y))*std(y)/std(x)
intercept = mean(y)-slope*mean(x)
MSE = (var(y)-cov(x, y)^2/var(x))*n1/df
SEintercept = sqrt(MSE*(1/n+mean(x)^2/var(x)/n1))
SEslope = sqrt(MSE/var(x)/n1)
alpha = (1-sig)/2
df = n - 2
t = quantile(TDist(df), [alpha, 1-alpha])
CLintercept = intercept .+ t .* SEintercept
CLslope = slope .+ t .* SEslope
@printf(" Estimate S.E. %6.3f%% %6.3f%%\n", alpha, 1-alpha)
@printf("Intercept: %8.7g %8.7g [%8.7g, %8.7g]\n", intercept, SEintercept, CLintercept[1], CLintercept[2])
@printf("Slope: %8.7g %8.7g [%8.7g, %8.7g]\n", slope, SEslope, CLslope[1], CLslope[2])
plotrma(x, y, intercept, slope, col1, col2, xlab, ylab, legend)
Dict(:intercept => intercept, :SEintercept => SEintercept,
:CLintercept => CLintercept, :slope => slope,
:SEslope => SEslope, :CLslope => CLslope)
end
function plotrma(x, y, intercept, slope, col1, col2, xlab, ylab, legend)
abline(intercept, slope, col, label) =
plot!([minx, maxx],
[slope * minx + intercept, slope * maxx + intercept],
color=col, label=label, legend=legend)
function lm(x, y)
b = cov(x, y)/var(x)
return mean(y) - b * mean(x), b
end
minx, maxx = extrema(x)
margin = (maxx - minx) * 0.05
minx -= margin
maxx += margin
pyplot()
plt = scatter(x, y, xlabel=xlab, ylabel=ylab, color=col1, label="")
abline(intercept, slope, col1, "Reduced Major Axis")
a, b = lm(x, y)
abline(a, b, col2, "linear regression")
display(plt)
end
y = [61, 37, 65, 69, 54, 93, 87, 89, 100, 90, 97]
x = [14, 17, 24, 25, 27, 33, 34, 37, 40, 41, 42]
a = rma(x, y, legend=:top)
Estimate S.E. 0.025% 0.975%
Intercept: 12.19378 10.54975 [-11.67141, 36.05898]
Slope: 2.119366 0.3324959 [1.367208, 2.871524]
a = rma(x, y, sig=0.9, legend=:top)
Estimate S.E. 0.050% 0.950%
Intercept: 12.19378 10.54975 [-7.145098, 31.53267]
Slope: 2.119366 0.3324959 [1.509864, 2.728869]