class Charty::Table::HashGroupBy
Public Class Methods
new(table, grouper, sort, drop_na)
click to toggle source
# File lib/charty/table.rb, line 137 def initialize(table, grouper, sort, drop_na) @table = table @grouper = check_grouper(grouper) init_groups(sort, drop_na) end
Public Instance Methods
[](key)
click to toggle source
# File lib/charty/table.rb, line 224 def [](key) return nil unless @indices.key?(key) index = @indices[key] Charty::Table.new( @table.column_names.map {|col| [col, @table[col].values_at(*index)] }.to_h, index: index ) end
apply(*args, &block)
click to toggle source
# File lib/charty/table.rb, line 207 def apply(*args, &block) Charty::Table.new( each_group.map { |_key, table| block.call(table, *args) }, index: Charty::Index.new(@indices.keys, name: @grouper) ) end
each_group() { |key, self| ... }
click to toggle source
# File lib/charty/table.rb, line 216 def each_group return enum_for(__method__) unless block_given? @indices.each_key do |key| yield(key, self[key]) end end
each_group_key(&block)
click to toggle source
# File lib/charty/table.rb, line 203 def each_group_key(&block) @indices.each_key(&block) end
group_keys()
click to toggle source
# File lib/charty/table.rb, line 199 def group_keys @indices.keys end
indices()
click to toggle source
# File lib/charty/table.rb, line 195 def indices @indices.dup end
Private Instance Methods
check_grouper(grouper)
click to toggle source
# File lib/charty/table.rb, line 143 def check_grouper(grouper) case grouper when Symbol, String, Array # TODO check column existence return grouper when Charty::Vector if @table.length != grouper.length raise ArgumentError, "Wrong number of items in grouper array " + "(%p for %p)" % [val.length, @table.length] end return grouper when ->(x) { x.respond_to?(:call) } raise NotImplementedError, "A callable grouper is unsupported" else raise ArgumentError, "Unable to recognize the value for `grouper`: %p" % val end end
init_groups(sort, drop_na)
click to toggle source
# File lib/charty/table.rb, line 164 def init_groups(sort, drop_na) case @grouper when Symbol, String column = @table[@grouper] @indices = (0 ... @table.length).group_by do |i| column.data[i] end when Array @indices = (0 ... @table.length).group_by { |i| @grouper.map {|j| @table[j].data[i] } } when Charty::Vector @indices = (0 ... @table.length).group_by do |i| @grouper.data[i] end end if drop_na case @grouper when Array @indices.reject! {|key, | key.any? {|k| Util.missing?(k) } } else @indices.reject! {|key, | Util.missing?(key) } end end if sort @indices = @indices.sort_by {|key, | key }.to_h end end