0
$\begingroup$

I have a list of lists, and I displayed it in grid format. The grid is huge, so I will show here an example:

list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}}
Grid[list, Frame -> All]

Now, I would like to export the data in Csv format, so to have 5 variables. What I did so far is:

Export["list.csv", list, "CSV"]

Problem is that in this way I have only four variables. What I need to do is to "split" the last column in two variables. Indeed, for each row it contains two values. So, in other words, I need to export a data set with five variables (the first column, the second column, the third column, and the values in the last column).

In another grid I have a similar but more complicated issue. Here it is:

list2 = {{2, 2, 2, {{1, 3} , {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}}
Grid[list2, Frame -> All]

As you can see, here sometimes I have two pairs of solutions in the last columns, sometimes only one. The data set I would like to export from that is similar to the first one. So, the first three variables correspond to the values in the first three columns. Moreover, I would like to extrapolate 4 variables from the last column (if it reports only a pair of solution, the last two variables should have missing values or whatever). Can someone help me please?

Bonus question: is it possible to name the columns of the grid, so to export a data set with the first row containing the name of the variables?

$\endgroup$

1 Answer 1

2
$\begingroup$

Is this what you are looking for?

list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}};

listf = Flatten /@ list
(* {{2, 2, 2, 1, 3}, {2, 1, 2, 1, 2}, {1, 2, 2, 1, 4}} *)

list2 = {{2, 2, 2, {{1, 3}, {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}};

list2f = Flatten /@ list2
(* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4}} *)

max = Length /@ list2f // Max;

PadRight[#, max, Null] & /@ list2f
(* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4, Null, Null}} *)

To add column headings

listf // Prepend[{"a", "b", "c", "d", "e"}]
$\endgroup$
2
  • $\begingroup$ Yes, that is perfect, thank you! $\endgroup$ May 10, 2020 at 19:30
  • $\begingroup$ @PlasticMan You are welcome, thanks for the accept. $\endgroup$ May 10, 2020 at 23:09

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.