Module: DescriptiveStatistics::CentralTendency

Included in:
AllMethods
Defined in:
lib/descriptive-statistics/central-tendency.rb

Instance Method Summary collapse

Instance Method Details

#meanObject



11
12
13
14
# File 'lib/descriptive-statistics/central-tendency.rb', line 11

def mean
  return if length < 1
  sum / length.to_f
end

#medianObject



16
17
18
19
20
21
22
23
24
25
# File 'lib/descriptive-statistics/central-tendency.rb', line 16

def median
  return if length < 1
  sorted = self.sort

  if length % 2 == 0
    (sorted[(length/2) -1 ] + sorted[length / 2]) / 2.0
  else
    sorted[length / 2]
  end
end

#modeObject



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/descriptive-statistics/central-tendency.rb', line 27

def mode
  return if length < 1
  frequency_distribution = inject(Hash.new(0)) { |hash, value| hash[value] += 1; hash }
  top_2 = frequency_distribution.sort { |a,b| b[1] <=> a[1] } .take(2)
  if top_2.length == 1
    top_2.first.first # Only one value in distribution, so it's the mode.
  elsif top_2.first.last == top_2.last.last
    nil # Equal frequency, no mode.
  else
    top_2.first.first # Most frequent is mode.
  end
end

#sum(identity = 0, &block) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/descriptive-statistics/central-tendency.rb', line 3

def sum(identity = 0, &block)
  if block_given?
    DescriptiveStatistics::Stats.new(map(&block)).sum(identity)
  else
    inject(:+) || identity
  end
end