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
?
Usually it's not a good practice to evaluate string as codebut here is a way to do it.
library(data.table)
for (row in 1:nrow(var_exp)) {
varname <- var_exp[row, "varname"]
expr <- var_exp[row, "expr"]
eval(parse(text = sprintf('DT[, %s := %s]', varname, expr)))
}
DT
# id value1 value2 ratio sum
#1: a 1 2 50 3
#2: b 3 4 75 7
We can do this with lapply
DT[, (var_exp$varname) := setDT(var_exp)[, lapply(sprintf("DT[,%s]",
expr), function(x) eval(parse(text = x)))]]
DT
id value1 value2 ratio sum
1: a 1 2 50 3
2: b 3 4 75 7
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.