Class: LEWT::PearsonR

Inherits:
MetaMath show all
Defined in:
lib/extensions/metastat/metamath.rb

Overview

This subclass performs a Pearson Correlation analysis on an x/y dataset.

Instance Method Summary collapse

Methods inherited from MetaMath

#descriptive_stats, #mean, #median, #mode

Constructor Details

#initialize(xs, ys) ⇒ PearsonR

Returns a new instance of PearsonR.



55
56
57
58
# File 'lib/extensions/metastat/metamath.rb', line 55

def initialize (xs, ys)
  raise Exception "_x & _y datasets must be of equal length" if xs.length != ys.length
  @xs, @ys = xs, ys
end

Instance Method Details

#correlate(xs = @xs, ys = @ys) ⇒ Object

Returns a Pearson Correlation R value

xs

The x series array of values

ys

The y series array of values



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/extensions/metastat/metamath.rb', line 63

def correlate(xs = @xs, ys = @ys)
  raise Exception "_x & _y datasets must be of equal length" if xs.length != ys.length
  x_mean = mean(@xs)
  y_mean = mean(@ys)
  numerator = (0...@xs.length).reduce(0) do |sum, i|
    sum + ((@xs[i] - x_mean) * (@ys[i] - y_mean))
  end
  denominator = @xs.reduce(0) do |sum, x|
    sum + ((x - x_mean) ** 2)
  end      
  (numerator / Math.sqrt(denominator))
end