# Differentiate values inside Table using Dynamic

I would have thought that the following code would let each indexed variable take its value from the SetterBar. Instead, all the SetterBars take the same value, as the image illustrates. Essentially all the SetterBars set the value of var[j] instead of each setting the value of variables var[1], var[2], etc. How can I get Mathematica to evaluate the indices when assigning values using the SetterBars inside the Table?

TableForm[
Table[{"Variable " <> ToString[var[j]],
SetterBar[
Dynamic@var[j], {0 -> "negative", 1 -> "positive",
2 -> "ignore"}]}, {j, 5}]]


It's a scoping issue. You can use With to get the expected behavior.

Column[{
TableForm[
Table[With[{j = j}, {"Variable " <> ToString[var[j]],
SetterBar[Dynamic@var[j], {0 -> "negative", 1 -> "positive", 2 -> "ignore"}]}],
{j, 5}]],
Table[With[{j = j}, Dynamic@var[j]], {j, 5}]}
]


• Fabulous, many thanks. Could you please explain Ma's scoping principles? Is there a logic of which commands prevent the evaluation of their contents and which do not? Apr 1, 2017 at 23:31
• @NicholasG "Table effectively uses Block to localize values or variables." [Table] Apr 1, 2017 at 23:36
• @NicholasG Scoping Constructs Apr 1, 2017 at 23:37
• Why does the variable name get substituted by its value when I reevaluate this? TableForm[ Table[{"Variable " <> ToString[var[j]], With[{j = j}, SetterBar[ Dynamic@var[j], {0 -> "liberal", 1 -> "conservative", 2 -> "ignore"}]]}, {j, 5}]] Apr 1, 2017 at 23:51
• @NicholasG Or use ToString[Unevaluated@var[j]] instead. Apr 1, 2017 at 23:55