I want to add a column to a data.table. But the name of this new column have to be extract from a character vector. I write this :
add_var=function(index){
label=c("products","price")
var_name=label[index]
df=data.frame(x=c(1,2,5,9),y=c(5,2,6,7))
dt=as.data.table(df)
dt[,(as.name(var_name)):=5]
return(dt)
}
new_ds=add_var(1)
And I expected something like
x y products
1 5 5
2 2 5
5 6 5
9 7 5
But, instead, I got this error message :
Error in `[.data.table`(dt, , `:=`((as.name(var_name)), 5)) :
LHS of := must be a symbol, or an atomic vector (column names or positions).
Anyone know how to fix my function to make it work?