From 947606978c1f8c8dbdca31e4c4d2dd370a3018bb Mon Sep 17 00:00:00 2001 From: Heng Li Date: Wed, 20 Apr 2011 23:09:23 -0400 Subject: [PATCH] added Pearson correlation coefficient --- lua/klib.lua | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/lua/klib.lua b/lua/klib.lua index e404c12..68e5d37 100644 --- a/lua/klib.lua +++ b/lua/klib.lua @@ -40,6 +40,7 @@ io.xopen() table.ksmall() table.shuffle() + table.pearson() math.lgamma() >math.lbinom() >math.igamma() math.igamma() matrix.chi2() math.erfc() @@ -178,6 +179,21 @@ function table.shuffle(a) end end +-- Description: Pearson correlation coefficient +function table.pearson(a) + local x1, y1 = 0, 0 + for _, v in pairs(a) do + x1, y1 = x1 + v[1], y1 + v[2] + end + x1, y1 = x1 / #a, y1 / #a + local x2, y2, xy = 0, 0, 0 + for _, v in pairs(a) do + local tx, ty = v[1] - x1, v[2] - y1 + xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty + end + return xy / math.sqrt(x2) / math.sqrt(y2) +end + -- -- Mathematics -- -- 2.47.3