Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/easystats.rb

Instance Method Summary collapse

Instance Method Details

#meanObject Also known as: average



2
3
4
5
6
# File 'lib/easystats.rb', line 2

def mean
  return if empty?

  sum / count.to_f
end

#medianObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/easystats.rb', line 24

def median
  return if empty?

  data = sort

  halfway = data.count / 2

  if data.count.even?
    (data[halfway] + data[halfway - 1]) / 2.0
  else
    data[halfway]
  end
end

#modeObject



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/easystats.rb', line 38

def mode
  return if empty?
  return first if one?
  return if self == uniq

  frequencies = inject(Hash.new(0)) { |k,v| k[v] += 1; k }
  frequencies = frequencies.sort_by { |k,v| v }

  return if frequencies[-1][1] == frequencies[-2][1]

  frequencies.last[0]
end

#probability_distributionObject



51
52
53
54
55
56
57
58
59
# File 'lib/easystats.rb', line 51

def probability_distribution
  return if empty?

  total = count.to_f

  uniq.inject({}) { |result, item|
    result.update({ item => count(item) / total })
  }
end

#rangeObject



61
62
63
64
65
# File 'lib/easystats.rb', line 61

def range
  return if empty?

  max - min
end

#standard_deviationObject



67
68
69
70
71
72
# File 'lib/easystats.rb', line 67

def standard_deviation
  return if empty?
  return 0 if one?

  Math::sqrt sum_of_deviations_squared / (count - 1)
end

#sumObject



74
75
76
# File 'lib/easystats.rb', line 74

def sum
  reduce :+
end

#varianceObject



78
79
80
81
82
# File 'lib/easystats.rb', line 78

def variance
  return if empty?

  sum_of_deviations_squared / count.to_f
end

#weighted_moving_averageObject



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/easystats.rb', line 10

def weighted_moving_average
  return if empty?
  return first if one?
  weighted_sum = 0
  sum = 0
  index = 0
  each do |element|
    weighted_sum = weighted_sum + (index * element)
    sum += index
    index += 1
  end
  weighted_sum.to_f / sum
end