]> git.kaiwu.me - klib.git/commitdiff
added Pearson correlation coefficient
authorHeng Li <lh3@live.co.uk>
Thu, 21 Apr 2011 03:09:23 +0000 (23:09 -0400)
committerHeng Li <lh3@live.co.uk>
Thu, 21 Apr 2011 03:09:23 +0000 (23:09 -0400)
lua/klib.lua

index e404c12a170f72d616ebc11ee57e79220282f53a..68e5d377dbdb32eecabff3c22bcdabaf2f183efb 100644 (file)
@@ -40,6 +40,7 @@
   io.xopen()
   table.ksmall()
   table.shuffle()
+  table.pearson()
   math.lgamma() >math.lbinom() >math.igamma()
   math.igamma() <math.lgamma() >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
 --