Module: DF::Filter

Included in:
DataFrame
Defined in:
lib/data_frame/core/filter.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#filter(as = Array, &block) ⇒ Object



18
19
20
21
# File 'lib/data_frame/core/filter.rb', line 18

def filter(as=Array, &block)
  new_data_frame = self.clone
  new_data_frame.filter!(as, &block)
end

#filter!(as = Array, &block) ⇒ Object

Takes a block to evaluate on each row. The row can be converted into an OpenStruct or a Hash for easier filter methods. Note, don’t try this with a hash or open struct unless you have facets available.



7
8
9
10
11
12
13
14
15
16
# File 'lib/data_frame/core/filter.rb', line 7

def filter!(as=Array, &block)
  as = infer_class(as)
  items = []
  self.items.each do |row|
    value = block.call(cast_row(row, as))
    items << row if value
  end
  @items = items.dup
  self
end

#filter_by_category(hash) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/data_frame/core/filter.rb', line 23

def filter_by_category(hash)
  new_data_frame = self.dup
  hash.each do |key, value|
    key = key.to_underscore_sym
    next unless self.labels.include?(key)
    value = [value] unless value.is_a?(Array) or value.is_a?(Range)
    new_data_frame.filter!(:hash) {|row| value.include?(row[key])}
  end
  new_data_frame
end

#filter_by_category!(hash) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/data_frame/core/filter.rb', line 34

def filter_by_category!(hash)
  hash.each do |key, value|
    key = key.to_underscore_sym
    next unless self.labels.include?(key)
    value = [value] unless value.is_a?(Array) or value.is_a?(Range)
    self.filter!(:hash) {|row| value.include?(row[key])}
  end
end