Mathematica Asked by JoutlawPhysics on August 12, 2021
This is literally a follow-up to part of Mr.Wizard’s answer to: Plot, extract data to a file
Specifically in reference to
multidat = Cases[First @ gr, Line[data_] :> data, -4];
We could then export each part to a separate file like this:
Export["file" <> IntegerString[#2] <> ".txt", #, "Table"] & ~MapIndexed~ multidat
{"file1.txt", "file2.txt", "file3.txt"}
First, may I please get confirmation that I’m correctly reading the ~
s in the middle line as the infix version of
MapIndexed[Export["file" <> IntegerString[#2] <> ".txt", #, "Table"]&, multidat]
?
Second, is there a simple way to export multidat
into a single file with the lines as pairs of columns? I.e., suppose multidat
is
{{{a1,a2},{b1,b2},{c1,c2}},
{{p1,p2},{q1,q2},{r1,r2},{s1,s2}},
{{x1,x2},{y1,y2},{z1,z2}}}
How would you turn that into
{{a1,a2,p1,p2,x1,x2},
{b1,b2,q1,q2,y1,y2},
{c1,c2,r1,r2,z1,z2}},
{,,s1,s2,,}}
?
Admittedly, I’m not sure how Mma would handle that last row. The data I have in mind is destined for a spreadsheet-like presentation where cells can be empty. Thanks for your help!
Firstly, you are right about Infix
as a very short experiment can verify. I will not comment on this further.
x ~ f ~ y === f[x, y]
Regarding the reshaping of your data, let me walk you through a possible solution.
l = {
{{a1, a2}, {b1, b2}, {c1, c2}},
{{p1, p2}, {q1, q2}, {r1, r2}, {s1, s2}},
{{x1, x2}, {y1, y2}, {z1, z2}}
}
Firstly, you probably will want to pad the list, such that the array is rectangular. I suggest here the padding {"", ""}
. However, other paddings might be more suitable for your problem.
lPadded = PadRight[#, Max[Length[#] & /@ l], {{"", ""}}] & /@ l;
Then you can use Flatten
to transpose everything to the form you want.
lReshaped = Flatten[lPadded, {{2}, {1, 3}}];
Finally, you can export the resulting list.
Export["mydata.csv", lReshaped]
Answered by Natas on August 12, 2021
Join[##, 2] & @@ PadRight[multidat, Automatic, ""]
{{a1, a2, p1, p2, x1, x2}, {b1, b2, q1, q2, y1, y2}, {c1, c2, r1, r2, z1, z2}, {"", "", s1, s2, "", ""}}
Alternatively,
MapAt[ArrayPad[#, 2, ""] &, Join[##, 2] & @@ multidat, {-1}]
{{a1, a2, p1, p2, x1, x2}, {b1, b2, q1, q2, y1, y2}, {c1, c2, r1, r2, z1, z2}, {"", "", s1, s2, "", ""}}
Answered by kglr on August 12, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP