Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active October 3, 2020 17:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/b56131a6385bf52bdd0a to your computer and use it in GitHub Desktop.
Save komasaru/b56131a6385bf52bdd0a to your computer and use it in GitHub Desktop.
Ruby script to calculate a correlation coefficient.
#*********************************************
# Ruby script to calculate a correlation coefficient.
#*********************************************
#
class Array
def r(y)
# 以下の場合は例外スロー
# - 引数の配列が Array クラスでない
# - 自身配列が空
# - 配列サイズが異なれば例外
raise "Argument is not a Array class!" unless y.class == Array
raise "Self array is nil!" if self.size == 0
raise "Argument array size is invalid!" unless self.size == y.size
# x の相加平均, y の相加平均 (arithmetic mean)
mean_x = self.inject(0) { |s, a| s += a } / self.size.to_f
mean_y = y.inject(0) { |s, a| s += a } / y.size.to_f
# x と y の共分散の分子 (covariance)
cov = self.zip(y).inject(0) { |s, a| s += (a[0] - mean_x) * (a[1] - mean_y) }
# x の分散の分子, y の分散の分子 (variance)
var_x = self.inject(0) { |s, a| s += (a - mean_x) ** 2 }
var_y = y.inject(0) { |s, a| s += (a - mean_y) ** 2 }
# 相関係数 (correlation coefficient)
r = cov / Math.sqrt(var_x)
r /= Math.sqrt(var_y)
end
end
ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p ary.r([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
p ary.r([2, 3, 3, 4, 6, 7, 8, 9, 10, 11])
p ary.r([15, 13, 12, 12, 10, 10, 8, 7, 4, 3])
@wrzasa
Copy link

wrzasa commented Oct 3, 2020

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment