If I have a table of data and I want to do a specific operation on say the third column, I usually do something like this:
OperatedOnTable =
MyTable /. {Col1_, Col2_, Col3_, Col4_} -> {Col1, Col2, 2*Pi*Col3 + 42, Col4}
where MyTable
has four columns in this case.
This is fine when I have a table with several columns, but when I have a table that has, say, twenty columns, this quickly becomes unwieldy and silly, as I need to map every single column such that I may pick out the columns I want to operate on.
For tables with large numbers of columns, how can I perform an operation on a specific column or column?
I should add, it would be preferable to be able to perform operations on multiple columns as is possible with my example, e.g.
OperatedOnTable =
MyTable /.
{Col1_, Col2_, Col3_, Col4_} -> {Col1 + 1/137, Col2, 2*Pi*Col3 + 42, Col4}
Note that I have performed two distinct operations on two distinct columns with a single command. I'd like to be able to replicate this functionality.
I want to achieve the same functionality as:
OperatedOnTable =
MyTable /.
{Col1_, Col2_, Col3_, Col4_, Col5_, Col6_, Col7_, Col7_, Col8_,
Col9_, Col10_, Col11_, Col12_, Col13_, Col14_, Col15_, Col16_} ->
{Col1 + 1/137, Col2, 2*Pi*Col3 + 42, Col4, Col5, Col6, Col7, Col7, Col8,
Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16}
This achieves what I want, manipulation of multiple columns in a single operation, but as we can see it is somewhat silly for tables with tens of columns.
I'm using Mathematica 12.1.1.0.
MyTable = MapAt[2*Pi*#+ 42&, MyTable, {All, 3}]
? $\endgroup$MyTable[[All, 3]] = 2*Pi*MyTable[[All, 3]] + 42
? $\endgroup$myTable = Array[a, {4, 4}]; myTable = MapAt[foo, myTable, {All, 3}];myTable
andmyTable = Array[a, {4, 4}]; myTable[[All, 3]] = foo /@ myTable[[All, 3]];myTable
you can see that both methods modify the third column ofmyTable
. $\endgroup$OperatedOnTable = MyTable /. {Col1_, Col2_, Col3_, Col4_}->{Col1 + 1/137, Col2, 2*Pi*Col3 + 42, Col4}
. It's also very clear to see what one has done, but for more than say eight or ten columns it gets a bit silly. $\endgroup$