How to paste in data.table using a vector as column reference?

Solution for How to paste in data.table using a vector as column reference?
is Given Below:

I’m creating a function where I need to paste an text with the values in a random column passed by the user. Suppose I have the following data

dt <- data.table(id = letters[1:10], amount = 1:10)
dt

What I’m trying to do is given a vector which is column name in the data use it to paste like

dt[,id:=paste0('id_',id)]
      id amount
 1: id_a      1
 2: id_b      2
 3: id_c      3
 4: id_d      4
 5: id_e      5
 6: id_f      6
 7: id_g      7
 8: id_h      8
 9: id_i      9
10: id_j     10

So if var is the vector what I tried is

var <- 'id'
dt[,(var):=paste0('id_',eval(var))]

but it returns

       id amount
 1: id_id      1
 2: id_id      2
 3: id_id      3
 4: id_id      4
 5: id_id      5
 6: id_id      6
 7: id_id      7
 8: id_id      8
 9: id_id      9
10: id_id     10

How I can make this be interpreted as a column name in the data.table?

We could use get

dt[, (var) := paste0('id_', get(var))]

-output

> dt
      id amount
 1: id_a      1
 2: id_b      2
 3: id_c      3
 4: id_d      4
 5: id_e      5
 6: id_f      6
 7: id_g      7
 8: id_h      8
 9: id_i      9
10: id_j     10

Or the standard way is .SD or .SDcols

dt[, (var) := paste0('id_', .SD[[var]])]

Maybe you can use str2lang within eval

> dt[, (var) := paste0("id_", eval(str2lang(var)))][]
      id amount
 1: id_a      1
 2: id_b      2
 3: id_c      3
 4: id_d      4
 5: id_e      5
 6: id_f      6
 7: id_g      7
 8: id_h      8
 9: id_i      9
10: id_j     10

Another option, if you don’t want to rewrite the expression:

var="id"
ex = substitute(
    dt[, var := paste0('id_', var)], 
    list(var = as.name(var))
)
eval(ex)

Using dt and var as names might lead to headaches, as these are names of functions included with R.