I'm trying to assign new variables to a data.table based on formulas which I have in a pre-existing data.frame, by looping over the data.frame, like this:
# Setup
DT <- data.table(id = c("a", "b"), value1 = c(1, 3), value2 = c(2,4))
var_exp = data.frame(varname = c("ratio", "sum"),
expr = c("(value1 / value2) * 100",
'rowSums(.SD, na.rm=TRUE), .SDcols=c("value1", "value2")'),
stringsAsFactors=FALSE)
# Assign new variables
for (row in 1:nrow(var_exp)) {
varname <- var_exp[row, "varname"]
expr <- var_exp[row, "expr"]
DT[, (varname) := eval(parse(text = expr))]
}
The first expression is understood without problems. However, the second expression returns an error because there is a comma in the expression:
Error in parse(text = expr) : <text>:1:29: unexpected ','
1: lapply(.SD, sum, na.rm=TRUE),
How can I pass this expression to data.table?