I have a data.table and a list of formulas,
DT <- data.table(A = c(1:3), B = c(3:1), C = c(4:6), D = (6:4))
l <- list(f1 = "A + B", f2 = "B + C", f3 = "C - D", f4 = "D / A")
This can be achieved by
DT[, ":="(f1 = A + B, f2 = B + C, f3 = C - D, f4 = D / A)]
or
for (i in 1:length(l)) {
DT[, eval(names(l)[i]) := eval(parse(text=l[[i]]))]
}
Is there a way to do this using the information in l
without using loop?
# some code
DT
# A B C D f1 f2 f3 f4
# 1: 1 3 4 6 4 7 -2 6.000000
# 2: 2 2 5 5 4 7 0 2.500000
# 3: 3 1 6 4 4 7 2 1.333333