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

Viewed 1123

Some toy data

set.seed(123)
df <- data.frame(what_ever = rnorm(5, 50, 1),
                 this_is = rnorm(5, 30, 1),
                 wtf_nnn = rnorm(5, 20, 1),
                 hat_ever = rnorm(5, 50, 1),
                 who_is = rnorm(5, 30, 1),
                 mmm_nnn = rnorm(5, 20, 1)                 
                 )


library(data.table)
DT <- data.table(df)

str(DT)
Classes ‘data.table’ and 'data.frame':  5 obs. of  6 variables:

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 <- names(df)
nm1 <- nm[1:3]
nm2 <- nm[4:6]

I would like to update DT this way, and the loop throught

i <- 1

New_Var_names <- paste("New_Var_", i, sep = "")
New_Var <- sprintf("%s/%s", nm1[i], nm2[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 Answers
Related