[R] Equation as a character string

Rui Barradas rui1174 at sapo.pt
Thu Mar 15 17:58:23 CET 2012


Hello,

>
> 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 
> 

Yes, eval/parse is discouraged but there's a way of using it,
that is less troublesome, to create a function.

(Maybe Emily was thinking of symbolic mathematics software - my personal
favorite is
Maple but there is also open source Maxima)


makefun <- function(text){
	x <- numeric()
	function(x) eval(parse(text=text))
}

txt <- 'x^2 + x + 5'

g <- makefun(txt)

g(6)
g(c(6, 5, 3, 10, 20))

(opt <- optimize(g, interval=c(-300, 300)))
curve(g, from=-5, to=5)
points(opt$minimum, opt$objective, col='red')


This may be usefull if you don't know the function's analytic expression
beforehand.

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/Equation-as-a-character-string-tp4474212p4475671.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list