Module: Nuggets::Array::CorrelationMixin
- Included in:
- Array
- Defined in:
- lib/nuggets/array/correlation_mixin.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#correlation_coefficient ⇒ Object
(also: #corr, #pmcc)
call-seq: array.correlation_coefficient => anArray.
Class Method Details
.included(base) ⇒ Object
33 34 35 |
# File 'lib/nuggets/array/correlation_mixin.rb', line 33 def self.included(base) base.send :include, Nuggets::Array::StandardDeviationMixin end |
Instance Method Details
#correlation_coefficient ⇒ Object Also known as: corr, pmcc
call-seq:
array.correlation_coefficient => anArray
Calculates the Pearson product-moment correlation coefficient for the {x,y}
pairs in array. If array only contains values instead of pairs, y
will be the value and x
will be each value’s position (rank) in array.
45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/nuggets/array/correlation_mixin.rb', line 45 def correlation_coefficient return 0.0 if empty? target = first.respond_to?(:to_ary) ? self : self.class.new(size) { |i| [i + 1, at(i)] } c = target.cov (sx = target.std { |x, _| x }).zero? || (sy = target.std { |_, y| y }).zero? ? c < 0 ? -1.0 : 1.0 : c / (sx * sy) end |