Unpivot a table 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 *)