Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/crunchr/active_record.rb,
lib/crunchr/core_ext.rb
Overview
stuff for dealing with statistics
monkey patches Hash, Array, ActiveRecord::Base and ActiveRecord::Relation
Instance Method Summary collapse
- #mean ⇒ Object
- #median ⇒ Object
- #mode ⇒ Object
- #range ⇒ Object
- #stddev ⇒ Object
- #sum ⇒ Object
-
#timed_interval(length, amount = 1) ⇒ Object
return an array of arrays where each inner array represents a period of time.
Instance Method Details
#mean ⇒ Object
30 31 32 |
# File 'lib/crunchr/core_ext.rb', line 30 def mean (self.sum * 1.0) / self.count end |
#median ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/crunchr/core_ext.rb', line 38 def median center = (self.count + (self.count % 2)) / 2 list = self.sort self.count % 2 == 0 ? [ list[center - 1], list[center] ].mean : list[center - 1] end |
#mode ⇒ Object
52 53 54 55 56 |
# File 'lib/crunchr/core_ext.rb', line 52 def mode counts = {} self.collect { |i| counts[i] ||= 0; counts[i] += 1 } counts.key(counts.values.sort.last) end |
#range ⇒ Object
47 48 49 50 |
# File 'lib/crunchr/core_ext.rb', line 47 def range list = self.sort list.last - list.first end |
#stddev ⇒ Object
34 35 36 |
# File 'lib/crunchr/core_ext.rb', line 34 def stddev Math.sqrt(self.collect{ |i| (i - self.mean) ** 2 }.sum) / Math.sqrt(self.count - 1) end |
#sum ⇒ Object
26 27 28 |
# File 'lib/crunchr/core_ext.rb', line 26 def sum self.inject(0.0) { |s, i| (s += i) rescue s } end |
#timed_interval(length, amount = 1) ⇒ Object
return an array of arrays where each inner array represents a period of time
Synopsis
timed_interval(:week, 2) # two week periods
timed_interval(:month, 6) # half year periods
timed_interval(:day, 1) # per day
Prerequisites
The items in the list must respond_to interval_time and it must return something that responds to < or >
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/crunchr/active_record.rb', line 19 def timed_interval(length, amount=1) list = self.sort_by(&:created_at) current = list.first.interval_time(length) records = [] period = [] list.each do |record| if record.interval_time(length) > (current + (amount - 1)) records << period period = [] current = record.interval_time(length) end period << record end records end |