Class: Glymour::Statistics::Variable

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, num_classes = nil, &block) ⇒ Variable

Returns a new instance of Variable.



22
23
24
25
26
27
28
29
# File 'lib/stats_module.rb', line 22

def initialize(name = nil, num_classes = nil, &block)
  @block = Proc.new &block
  @num_classes = num_classes
  @intervals = num_classes && variable_container ? set_intervals : nil
  
  # names are used as variable names in R, so make sure there's no whitespace
  @name = name.gsub(/\s+/, '_') if name
end

Instance Attribute Details

#intervalsObject

Returns the value of attribute intervals.



20
21
22
# File 'lib/stats_module.rb', line 20

def intervals
  @intervals
end

#nameObject

Returns the value of attribute name.



20
21
22
# File 'lib/stats_module.rb', line 20

def name
  @name
end

#num_classesObject

Returns the value of attribute num_classes.



20
21
22
# File 'lib/stats_module.rb', line 20

def num_classes
  @num_classes
end

#variable_containerObject

Returns the value of attribute variable_container.



20
21
22
# File 'lib/stats_module.rb', line 20

def variable_container
  @variable_container
end

Instance Method Details

#location_in_interval(row) ⇒ Object

Gives the location of a column value within a finite set of interval values (i.e. gives discrete state after classing a continuous variable)



54
55
56
57
58
59
60
61
# File 'lib/stats_module.rb', line 54

def location_in_interval(row)
  intervals.each_with_index do |x, i|
    return i if @block.call(row) <= x
  end

  # Return -1 if value is not within intervals
  -1
end

#set_intervalsObject

Apply @block to each column value, and return a list of evenly divided intervals [x1, x2, …, x(n_classes)] So that x1 is the minimum, xn is the max



34
35
36
37
38
# File 'lib/stats_module.rb', line 34

def set_intervals
  vals = self.values
  step = (vals.max - vals.min)/(num_classes-1).to_f
  @intervals = (0..(num_classes-1)).map { |k| vals.min + k*step }
end

#value_at(row) ⇒ Object



40
41
42
# File 'lib/stats_module.rb', line 40

def value_at(row)
  intervals ? location_in_interval(row) : @block.call(row)
end

#valuesObject

Gives an array of all variable values in table



45
46
47
48
49
50
51
# File 'lib/stats_module.rb', line 45

def values
  if variable_container.table < ActiveRecord::Base
    intervals ? variable_container.table.all.map { |row| location_in_interval(row) } : variable_container.table.map { |r| @block.call(r) }
  else
    intervals ? variable_container.table.map { |row| location_in_interval(row) } : variable_container.table.map(&@block)
  end
end