From: Heng Li Date: Thu, 21 Apr 2011 03:09:23 +0000 (-0400) Subject: added Pearson correlation coefficient X-Git-Tag: ksprintf-final~50 X-Git-Url: http://www.kaiwu.me/postgresql/commit/?a=commitdiff_plain;h=947606978c1f8c8dbdca31e4c4d2dd370a3018bb;p=klib.git added Pearson correlation coefficient --- 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 --