8
$\begingroup$

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

Input:

enter image description here

Output (transposed just to save space):

enter image description here

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

Addendum

Just in case: how to pivot in Mathematica

$\endgroup$
8
$\begingroup$

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]
$\endgroup$
4
$\begingroup$
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

Mathematica graphics

f2@list == f1@list

True

$\endgroup$
4
$\begingroup$

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 *)

$\endgroup$
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.