Module: CArray::TableMethods

Defined in:
lib/carray/table.rb

Overview

Column-name support for a 2-D CArray used as a table: an ordered name list alongside the data, plus name-based column access.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#column_namesObject

Returns the value of attribute column_names.



11
12
13
# File 'lib/carray/table.rb', line 11

def column_names
  @column_names
end

Instance Method Details

#column(name) ⇒ CArray?

Returns the column view identified by name. Integer names index the second axis directly; Symbol and String names look up the position in #column_names. Returns nil when the name is unknown.

Parameters:

  • name (Integer, Symbol, String)

    column identifier.

Returns:

  • (CArray, nil)

    column view or nil when unknown.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/carray/table.rb', line 41

def column (name)
  if name.is_a?(Integer)
    return self[false, name]
  elsif @column_names
    case name
    when Symbol
      if i = @column_names.index(name) or i = @column_names.index(name.to_s) 
        return self[false, i]
      end          
    when String
      if i = @column_names.index(name) or i = @column_names.index(name.intern) 
        return self[false, i]
      end
    end
  end
  return nil
end

#row(i) ⇒ Hash

Returns the i-th row as a Hash keyed by #column_names (falling back to 0-based Integer keys when none are set).

Parameters:

  • i (Integer)

    row index.

Returns:

  • (Hash)


64
65
66
67
68
69
70
71
72
# File 'lib/carray/table.rb', line 64

def row (i)
  keys = @column_names || (0...dim0).to_a
  output = {}
  data = self[i, nil]
  keys.each_with_index do |key, j|
    output[key] = data[j]
  end
  return output
end

#rows(arg) ⇒ CArray

Returns a fresh table copy holding the rows selected by arg, extended with CArray::TableMethods and carrying self's #column_names.

Parameters:

  • arg (Object)

    row selector accepted by self[arg, nil] (Integer, Range, boolean CArray, ...).

Returns:

  • (CArray)

    new table copy.



81
82
83
84
85
86
# File 'lib/carray/table.rb', line 81

def rows (arg)
  table = self[arg, nil].copy
  table.extend(CArray::TableMethods)
  table.column_names = @column_names
  return table
end

#select({ |table| ... }) {|table| ... } ⇒ CArray

Yields self and returns a new table restricted to the rows selected by the block's return value. The block may return an Integer index array or a boolean mask (which is converted via #where).

Yield Parameters:

Yield Returns:

Returns:

  • (CArray)

    filtered table copy.



96
97
98
99
100
101
102
103
# File 'lib/carray/table.rb', line 96

def select
  idx = yield(self)
  case idx.data_type
  when CA_BOOLEAN
    idx = idx.where
  end
  return rows(+idx)
end