I have data in ragged arrays of the form
$$\left( \begin{array}{cc} \text{x1} & \{\text{a1}\} \\ \text{x2} & \{\text{a2}\} \\ \text{x3} & \{\text{a3},\text{b3},\text{c3}\} \\ \text{x4} & \{\text{a4},\text{b4},\text{c4}\} \\ \text{x5} & \{\text{a5},\text{b5},\text{c5},\text{d5},\text{e5}\} \\ \text{x6} & \{\text{a6}\} \\ \text{x7} & \{\text{a7},\text{b7}\} \\ \text{x8} & \{\text{a8},\text{b8},\text{c8}\} \\ \text{x9} & \{\text{a9}\} \\ \end{array} \right)$$
and I wish to sort it into arrays such as $$\text{data1}=\left( \begin{array}{cc} \text{x1} & \text{a1} \\ \text{x2} & \text{a2} \\ \text{x3} & \text{a3} \\ \text{x4} & \text{a4} \\ \text{x5} & \text{a5} \\ \text{x6} & \text{a6} \\ \text{x7} & \text{a7} \\ \text{x8} & \text{a8} \\ \text{x9} & \text{a9} \\ \end{array} \right);$$
and $$\text{data2}=\left( \begin{array}{cc} \text{x3} & \text{b3} \\ \text{x4} & \text{b4} \\ \text{x5} & \text{b5} \\ \text{x7} & \text{b7} \\ \text{x8} & \text{b8} \\ \end{array} \right);$$
and $$\text{data3}=\left( \begin{array}{cc} \text{x3} & \text{c3} \\ \text{x4} & \text{c4} \\ \text{x5} & \text{c5} \\ \text{x8} & \text{c8} \\ \end{array} \right);$$
finally $$\text{data4}=\left( \begin{array}{cc} \text{x5} & \text{e5} \\ \end{array} \right);$$
The actual data is numeric and has many more rows and an unknown number of ragged columns.
I have been trying with Cases
but with no success so far.
Any ideas? Thanks
***** Edit *****
Thank you all for your efforts. There is much to learn from.
I have had a go at timing the individual offerings.
ClearAll[kglr, u1066, syed1, syed2, lericr, eldo]
nn = 5000 {3, 4, 5, 6, 7};
data = Flatten[
Table[{#[[1]], Rest[#]} & /@
RandomReal[{-1, 1}, {nn[[i]], i + 1}], {i, Length@nn}], 1];
tkglr = Timing[raggedThread = Flatten[Map[Thread]@#, {2}] &;
raggedThread@data;][[1]];
(* *)
tu1066 =
Timing[Through[(Cases[{x_, #} :> {x, y}] & /@
NestList[Prepend[_], {y_, ___}, 3])[data]];;][[1]];
(* *)
tsyed1 = Timing[Flatten[Thread /@ data, {{2}, {1}}];][[1]];
tsyed2 = Timing[tlist = Thread /@ data;
Clear[f];
f[k_List, n_Integer] :=
Scan[If[Length@# > n - 1, Sow[Part[#, n]], Nothing] &, k] //
Reap // Last // First;
f[tlist, #] & /@ Range[Max@(Length /@ tlist)];][[1]];
(* *)
tlericr =
Timing[Flatten[
Inner[Thread@*List, data[[All, 1]], data[[All, 2]],
List], {2}];][[1]];
(* *)
teldo = Timing[data1 = <|Rule @@@ data|>;
get[n_] := KeyValueMap[List]@DeleteMissing@Query[All, n]@data1;
{get[1], get[2], get[3], get[4], get[5]};][[1]];
(* *)
The results are
TableForm[{tkglr, tu1066, tsyed1, tsyed2, tlericr, teldo},
TableHeadings -> {{kglr, u1066, syed1, syed2, lericr, eldo}, None}]
$ \begin{array}{c|c} \text{kglr} & 0.140625 \\ \text{u1066} & 0.15625 \\ \text{syed1} & 0.140625 \\ \text{syed2} & 1.01563 \\ \text{lericr} & 0.171875 \\ \text{eldo} & 2.45313 \\ \end{array} $
So the methods of kglr and the first method of syed are the fastest.
Well done everyone
{x5, d5}
? $\endgroup$