eval(parse(text = ...), ...)
is what you're looking for.
I changed ln()
to log()
in your example because R doesn't understand ln()
...
dd <- read.table(header = TRUE, text = "
Price Quantity Formula
23 1 Price*exp(Quantity)
25 2 Price*log(Quantity)
61 1 Price*Quantity+35
")
efun <- function(p, q, form) {
eval(parse(text = form), list(Price = p, Quantity = q))
}
## run on first row
with(dd[1,], efun(Price, Quantity, Formula))
## run on all rows (and collapse from a list to a vector)
unlist(Map(efun, dd$Price, dd$Quantity, dd$Formula))
(or with(dd, unlist(Map(efun, Price, Quantity, Formula)))
)
As always when using eval()
you should be careful that you're not using user-provided input, or that you have sanitized it (so that someone doesn't sneak in malicious code)
If you have the input names as a vector (pars <- c("Price", "Quantity")
) it can still be done:
pars <- c("Price", "Quantity")
res <- rep(NA, nrow(dd))
for (i in seq(nrow(dd))) {
res[i] <- eval(parse(text = dd$Formula[i]), dd[i,pars])
}