How to generate a linear combination of variables and update table using data.table in a loop call?

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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)] 

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!