[R] Adding and Multiplying two Unevaluated Expressions

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Dec 2 18:18:57 CET 2009


Benjamin Müller wrote:
> HI,
> 
> As I'm trying to compute Taylor series, I'm having problems in adding and multiplying unevaluated expressions. I searched for a solution but found none.
> 
> my Taylor function works fine for evaluating functions as you can see here:
> 
> 
> rTaylorVal=function(exp,x0,dx,n) {
> 
> ls=list(x=x0)
> 
> newexp=eval(exp,ls)
> 
> exp0=exp
> 
> for (i in 1:n){
> exp0=D(exp0,"x")
> newexp=newexp+eval(exp0,ls)/factorial(i)*dx^i
> }
> 
> return(newexp)
> 
> }
> 
> Where exp is an expression like exp=expression(x^2*sin(x)), x0 is the startvalue, dx the difference between startvalue and searched value and n is the length of the series.
> 
> So I tried to remove dx as a value, to get a Taylor series expression, but it doesn't work as simple multiplication (*) and accumulation (+) is not good for expressions.
> 
> That's my point so far, now my question:
> 
> Is it actually possible to add and/or multiply expressions, and how?


Well, although R as a numerical language is not designed for these kind 
of things, you can do it, e.g. using a function

opExpr <- function(expr1, expr2, op = "+"){
     expr <- expression(a + b)
     expr[[1]][[1]] <- as.name(op)
     expr[[1]][[2]] <- expr1[[1]]
     expr[[1]][[3]] <- expr2[[1]]
     expr
}

that can construct such expressions as in:

opExpr(expression(x * sin(x)), expression(x^2 * sin(x)))
opExpr(expression(x * sin(x)), expression(x^2 * sin(x)), "*")

Best wishes,
Uwe Ligges



> Thank you so far.
> 
> Benjamin Müller
> Geographer (B.Sc.)
> 
>




More information about the R-help mailing list