packages

table::reshape

On this page

Long <-> wide: pivot spreads one column's values into columns, melt stacks columns into (variable, value) rows.

Implementations

impl Table

  • pub fn pivot(self, index: List<str>, columns: str, values: str, agg: AggKind) throws (TableError) -> Table§

    Source

    One row per distinct index key, one column per distinct value of columns (named by its text, in order of first appearance), each cell agg of the values rows with that pair; null where there are none.

    nabi
    use table::AggKind;
    let t = table::table!{
        "day": ["mon", "mon", "tue"],
        "city": ["A", "B", "A"],
        "temp": [20.0, 25.0, 22.0],
    };
    let p = try t.pivot(["day"], "city", "temp", AggKind::Mean) catch _ { t };
    assert(p.names() == ["day", "A", "B"]);
    assert(p.row(1).f64("B") is none);
    
  • pub fn melt(self, id_vars: List<str>, value_vars: List<str> | none) throws (TableError) -> Table§

    Source

    Stack the columns value_vars (none: every column not in id_vars) into two: variable with the column name and value with its cell, the id_vars repeated. Rows go column by column. The value columns need one type (i64 with f64 gives f64).

    nabi
    let t = table::table!{ "id": [1, 2], "a": [10, 20], "b": [30, 40] };
    let m = try t.melt(["id"], none) catch _ { t };
    assert(m.names() == ["id", "variable", "value"]);
    assert(m.nrows() == 4 && m.row(2).str("variable") == "b");