Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into a formula in R

Tags:

r

I have several formulas in string form, read from files, like this: "0.657 + 0.343*age - 1.239 * cholesterol" and I would like to convert each of these into a formula object to run on a data frame (ie. my.formula <- 0.657 + 0.343*age - 1.239 * cholesterol) . How can I do that programmatically?

like image 910
K Owen - Reinstate Monica Avatar asked Feb 03 '16 20:02

K Owen - Reinstate Monica


1 Answers

Use eval and parse

example:

> cholesterol <- 2  # set some values for cholesterol and age
> age <- 3
> eval(parse(text="0.657 + 0.343*age - 1.239 * cholesterol"))
[1] -0.792
like image 96
Jilber Urbina Avatar answered Oct 29 '22 17:10

Jilber Urbina