Some toy data
set.seed(123) df
How can I generate new variables in the data.table
that are the result of the following using a loop?
New_Var_1 = what_ever/hat_ever New_Var_2 = this_is/who_is New_Var_3 = wtf_nnn/mmm_nnn
Here i order the column names
nm
I would like to update DT this way, and the loop throught
i
Neither of the 3 attemps works.
DT[,New_Var_names := New_Var] DT[,cat(New_Var_names) := cat(New_Var)] DT[,eval(New_Var_names) := eval(New_Var)]
I'd recommend to use set
with a for-loop
to do this, but on the current stable (CRAN) version 1.8.10, set
doesn't add new columns. So, I'd do something like:
require(data.table) out_names
In the current devel version (1.8.11), set
can add new columns. So in that, you don't need the assignment using :=
. That is:
require(data.table) out_names
For completeness, another way is :
EVAL = function(...)eval(parse(text=paste0(...))) # helper function New_Var_names
This is more general in that you can also vary the operator /
in the sprintf
and vary the by=
clause too, etc. It's similar to constructing a dynamic SQL statement, if that helps. If you wanted to log the dynamic query being executed, you could add a cat
in your definition of EVAL
.