function - How to turn a simple text expression into a mathematical expression in R -


right trying solve question concerning establishing function calculate log of moment generating functions in r. required procedure user input random density function f(x) interval of random variable. however, have no idea how let r identify input string of function expression, "x^2-4*x", , turn workable mathematical expression or function. can help?

mgf <- function(expr, t, from=null, to=null){ moment <- null     (i in 1:length(t)){         moment <- c(moment,integrate(exp(x*t[i])*(expr),lower=from,upper=to))     } return(moment) } 

this code i'm having. obviously, won't work. want users can input expression, x^2-4*x, value of expr, , turn expr part of function integrate() function can evaluate.

you can try:

library(functional)  mgf = function(stringformula, t, from=null, to=null) {     f = function(x, i) exp(x*i)*eval(parse(text=stringformula))     sapply(t, function(u) integrate(curry(f, i=u), lower=from, upper=to)[[1]]) } 

the point is, need pass character string x variable in stringformula argument:

mgf("x^2-4*x", 1:5, from=0, to=1) #[1]  -3.281718  -6.791792 -14.652785 -32.698902 -74.976232 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -