1

I have formulas in a data frame :

Price Quantity Formula
23    1   Price*exp(Quantity) 
25    2   Price*ln(Quantity)
61    1   Price*Quantity+35

I would like to use these formulas (from the data frame) to make a calculation. Do you know if there is a way to do this calculation in R?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
ffff
  • 11
  • 1

1 Answers1

1

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])
}
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank you for your fast answer but running the code I have the following results : 1 2 3. You understand why? I tried several codes using eval and parse but not reaching for the good result at this moment. – ffff Oct 15 '22 at 21:14
  • I don't. For me, the last line of my code `unlist(...)` returns `62.52048 17.32868 96.00000`. If you give a **reproducible** example (edit your question to include it) someone might be able to help. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Ben Bolker Oct 15 '22 at 21:20
  • It is working now. It was due to the fact Formula's type was factor. Thanks for your input. Just one question, do you know if it is possible to enter a list for columns names (Price, Quantity) in order to automatize the code? – ffff Oct 16 '22 at 12:37