A little gem to help you pivot your arrays
Ruby
Switch branches/tags
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.document
.gitignore Initial commit to micro_pivot. Dec 12, 2010
LICENSE
README.md Update README.md Nov 2, 2011
Rakefile
VERSION
ms_pivot.gemspec Regenerated gemspec for version 0.1.3 Dec 16, 2010

README.md

Ms Pivot

by vWorkApp

A little gem to help you pivot your arrays.

my_array = [
  ["ProductA", "AU", 1],
  ["ProductA", "AU", 2],
  ["ProductB", "NZ", 3],
  ["ProductB", "US", 4],
]

pv = MsPivot::Table.new(my_array, 0, 1, MsPivot::SUM)
puts pv.inspect

#              AU  NZ  US
# ProductA     3   -   -
# ProductB     -   3   4

Install

sudo gem install ms_pivot

Usage

  • Specify which items (indicies) to use as row and column headers. All remaining items must have a measure specified.

      my_array = [
        ["ProductA", "AU", 1, "x"],
        ["ProductA", "AU", 2, "t"],
        ["ProductB", "NZ", 3, "z"],
        ["ProductB", "US", 4, "a"],
      ]
      pv = MsPivot::Table.new(my_array, 0, 1, MsPivot::SUM, MsPivot::COUNT)
    

    Item 0 is used as the row headers, item 1 is used as the column headers, item 2 and 3 are aggregated (summed and counted respectively).

  • Use of of the following built-in measures (i.e. methods to aggregate the grouped data)

    • MsPivot::SUM
    • MsPivot::COUNT
    • MsPivot::AVG
    • MsPivot::MIN
    • MsPivot::MAX
    • MsPivot::APPEND (builds an array of items)
    • MsPivot::SINGLE (returns a single item, and throws an exception otherwise)
  • Or specify your own measure function

      pv = MsPivot::Table.new(orig_array, 0, 1, MsPivot::Measure.new { |current_value, new_value|
        # sum of squares
        current_value ||= 0
        current_value + (new_value ** 2)
      end
    
  • Let Ms Pivot work out automatically what the column headers are from the data (in which case it'll order them alphabetically) or tell it explicitly what columns you want

      pv = MsPivot::Table.new(orig_array, 0, 1, MsPivot::SUM)
      pv.column_headers = ["AU", "US", "UK"]
    
  • Get the results out as an array

      a = pv.column_headers
      b = pv.to_a
    
      # a = ["AU", "NZ", "US"]
      # b = [
      #  ["ProductA", [3, 2], [], []],
      #  ["ProductB", [], [3, 1], [4, 1]]
      # ]
    
  • Or iterate over them

      pv.each do |row_header, columns| do
        columns.each do |col_header, values| do
          values.each do |value|
              // do stuff
          end
        end
      end
    

See /spec/pivot_spec.rb for some examples of Ms Pivot being used.

Todo

  • Write RDOC

Copyright

Copyright (c) 2010 VisFleet. See LICENSE for details.