# Unpivot a table in Mathematica

I've used a head-on way to unpivot a table but I feel there shoud be more succinct and simple forms. Ideas?

Input:

Output (transposed just to save space):

Long way from input to output:

list = {{Null, d, e}, {a, 1, 4}, {b, 2, 3}};

tmp = Thread[Tuples@{#[[2 ;;, 1]], #[[1, 2 ;;]]} -> Flatten@#[[2 ;;, 2 ;;]]] & @ list;
Flatten[Table[#, {#2}] & @@@ tmp, {1, 2}] // Transpose // TableForm


Just in case: how to pivot in Mathematica

You can use MapIndexed with ConstantArray like this:

f[n_, {v_, i_}] := ConstantArray[{list[[v + 1, 1]], list[[1, i + 1]]}, n];
Flatten[MapIndexed[f, list[[2 ;;, 2 ;;]], {2}], 2]

ClearAll[f1, f2]

f1 = ## & @@@ MapThread[ConstantArray,
{Tuples@{#[[2;;, 1]], #[[1, 2;;]]}, ## & @@@ #[[2;;, 2;;]]}] &;

f2 = ## & @@@ ConstantArray @@@ Flatten[{Outer[List, #[[2;;, 1]], #[[1, 2 ;;]]],
#[[2;;, 2;;]]}, {{2, 3}, {1}}] &;

f1@list // Transpose // MatrixForm


f2@list == f1@list


True

Corner Null suggests a nested Association approach:

ds = <|a -> <|d -> 1, e -> 4|>, b -> <|d -> 2, e -> 3|>|>


<|a -> <|d -> 1, e -> 4|>, b -> <|d -> 2, e -> 3|>|>

Then

Dataset[ds] [All, KeyValueMap[Table] /* Flatten][
KeyMap[List] /* KeyValueMap[List /* Tuples] /* (Flatten[#, 1] &)]


{{a, d}, {a, e}, {a, e}, {a, e}, {a, e}, {b, d}, {b, d}, {b, e}, {b,
e}, {b, e}} (* normal'd *)

With no other constraints or requirements of generality? Then I would write it like this:

list = {{Null, d, e}, {a, 1, 4}, {b, 2, 3}};

unpivot[{
{Null, d_, e_},
{a_, v1_, v2_},
{b_, v3_, v4_}
}] := Join[
ConstantArray[{a, d}, v1],
ConstantArray[{a, e}, v2],
ConstantArray[{b, d}, v3],
ConstantArray[{b, e}, v4]
]

unpivot[list]

(* Out: {{a, d}, {a, e}, {a, e}, {a, e}, {a, e}, {b, d}, {b, d},
{b, e}, {b, e}, {b, e}} *)


It's easy to understand, succinct, and wasn't hard to write down.