简体   繁体   中英

Convert a string into a formula in 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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM