2
$\begingroup$

I'm trying to restructure the following expression:

start = Table[{1, 2, 3, 4}, 5];
Join[{ToString /@ {first, second, third, fourth}},start]

Into this:

final =Table[{1, 4, 2, 3}, 5];
Join[{ToString /@ {first, fourth,second, third}},final]

Ideally I would like to do this with rules (i.e. exchange columns). It would be even better if I could do it by the column header name. Please assume the variables are not homogeneous throughout the column.

Thanks!

$\endgroup$
1
$\begingroup$

I think a simple way is just to swap columns directly. Why complicate things?

start = Table[{1, 2, 3, 4}, 5];
start = Join[{ToString /@ {first, second, third, fourth}}, start]

Mathematica graphics

Now just do

start[[All, {2, 3, 4}]] = start[[All, {4, 2, 3}]];

Mathematica graphics

Any reason why not do this?

If you really want to use rule, you could use

start = Table[{1, 2, 3, 4}, 5];
start = Join[{ToString /@ {first, second, third, fourth}}, start];
rules = {2 -> 4, 3 -> 4, 4 -> 1};

start[[All, {2, 3, 4}]] = start[[All, {2, 3, 4} /. rules]];
$\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.