Skip to content

Add pivot #7

@mrkn

Description

@mrkn

The pivot collects the result arrays of the given block, makes a hash that is made by grouping the item in the result arrays by its first items, then aggregates the values of the hash by the given a function or functions, finally returns the resulting hash.

[ 1, 2, 3, 4 ].pivot {|x| [x.odd?, x] } # aggregated by mean
#=> {true => 2.0, false => 3.0}

[ 1, 2, 3, 4 ].pivot(agg: :sum) {|x| [x.odd?, x] }
#=> {true => 4, false => 6}

[ 1, 2, 3, 4 ].pivot(agg: :itself) {|x| [x.odd?, x] }
#=> {true => [1, 3], false => [2, 4]}

[ 1, 2, 3, 4 ].pivot(agg: [:mean, :sum]) {|x| [x.odd?, x] }
#=> {true => [2.0, 4], false => [3.0, 6]}

[ 1, 2, 3, 4 ].pivot(agg: {x: :mean, y: :sum}) {|x| [x.odd?, x] }
#=> {true => { :x => 2.0, :y => 4}, false => { :x => 3.0, :y => 6}}

{ a: 1, b: 2, c: 1 }.pivot(agg: :itself) {|k, v| [v, k] }
#=> {1 => [:a, :c], 2 => [:b]}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions