How can I use Function and Slot with variable names in slot?

I am trying to use a Function in AggregateRows of Tabular data.
I need to add the values of several columns of the data.

I am using this expression:

ColumnKeys[itersela][[i]] -> 
 Function[   Total[ #[   ColumnKeys[itersela][[i]]   ]  ]    ]

But this doesn’t work. It works with specific names of Keys after #, but in this case, I will use variable Keys (the Key name is given by ColumnKeys[itersela][[i]] for several values of i.

How can I make this work?

You haven’t really provided enough info to be able to understand exactly what you’re working with. If the following doesn’t help, then please provide a minimal example of the tabular data you’re working with and the specific keys that you want to operate on. In the meantime, here’s my best guess…

Here’s a test Tabular:

tab = Tabular[{{"a", 1, 100}, {"b", 2, 200}, {"a", 3, 300}, {"b", 4, 400}}, {"col1", "col2", "col3"}]

AggregateRowsExample1.bmp (264 KB)

You said you want to get the columns from ColumnKeys and several indices, so I’m assuming you have a list of values for i that you will use to index into ColumnKeys[tab]. So for example, if your desired i values are {1,3}, we need to generate the argument to AggregateRows, which would be something like:

{"col1" -> Function[Total[#["col1"]]], "col3" -> Function[Total[#["col3"]]]}

One way is a simple Table:

Table[ColumnKeys[tab][[i]] -> Function[Evaluate[Total[#[ColumnKeys[tab][[i]]]]]], {i, {1, 3}}]
(* {"col1" -> (Total[#1["col1"]] &), "col3" -> (Total[#1["col3"]] &)} *)

The Evaluate is needed because Function holds its arguments unevaluated, and we need to actually extract the desired key to create the body of our function. Evaluate forces evaluation of arguments that would otherwise be held unevaluated.

Now just insert this into AggregateRows:

AggregateRows[tab, Table[ColumnKeys[tab][[i]] -> Function[Evaluate[Total[#[ColumnKeys[tab][[i]]]]]], {i, {1, 3}}]]

AggregateRowsExample.bmp (85.4 KB)

Is the ColumnKeys[itersela][[i]] a string? To obtain the symbol #colKey you may try StringJoin:

ColumnKeys[itersela][[i]] -> 
 Function[Total[ToExpression[StringJoin[{"#", ColumnKeys[itersela][[i]]}]]]]

Slightly easier would be to just use Slot

Thank you Eric. It works. You fully understood my problem.

This is my code and image of results:

tab = AggregateRows[ itersela,
Table[ ColumnKeys[itersela][[i]] → Function[ Evaluate[
Total[ #[ColumnKeys[itersela][[i]] ] ]
]]
, {i, 10, 22} ],
“ENTIDAD”
]

Thank you Gianluca. I couldn’t make it work this way. Eric’s solution worked!