[R] Equation as a character string
Joshua Wiley
jwiley.psych at gmail.com
Thu Mar 15 09:48:57 CET 2012
Hi Emily,
Yes (see below), but you might be better off by writing a simple
function. Here are examples both ways (usually eval parse is highly
discouraged).
Cheers,
Josh
#########################
eqn1string <- "x^2 + x + 5"
x <- 6
## works
eval(parse(text = eqn1string))
## better
f <- function(x) {
x^2 + x + 5
}
f(6)
## this is more flexible
f(c(6, 5, 3, 10, 20))
## plot function
curve(f, from = -20, to = 20)
## find minimum in a range
optimize(f = f, interval = c(-300, 300))
## minimum is the value of x that yields the smallest value of
## the objective function, i.e.
f(-.5)
#########################
On Wed, Mar 14, 2012 at 11:39 PM, Emily Weiser <emily.l.weiser at gmail.com> wrote:
> I'm trying to figure out if it's possible to use a character string as an
> equation, e.g:
>
> eqn1string <- "x^2 + x + 5"
>
> Then I want to tell R:
> 1) that eqn1string is actually an equation (even though it was stored as a
> character string), and
> 2) to apply the equation to a specified value of x (e.g. given x <- 6,
> what is the result of the equation).
>
> Thanks in advance for any insight anyone may be able to offer.
>
> Emily
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/
More information about the R-help
mailing list