How to combine expressions in R
I want to combine expressions by adding them together or by dividing (code below) and I get the error:
non-numeric argument for binary operator
How to get the combination?
a=0
fun2 = expression(sin(x))
fun4 = expression(sin(pi/4))
N=1
while(N<3){
fun1 = fun2
fun2 = D(fun1,"x")
fun3 = expression(fun2/(prod(1:N)*(x-1)^N))
fun4 = expression(fun4+fun3)
N=N+1
}
+3
source to share
1 answer
Here is a recursive implementation to build the taylor extension. The result is a "call" to the class, but you can evaluate it in the same way as an expression. It basically just creates an expression tree by adding each additional term in the taylor extension recursively.
taylor <- function(f, a, deg, curr=NULL) {
if (is.function(f)) f <- body(f) # use the body of the function for derivatives
## Base cases
if (missing(curr))
return( as.call(list(`+`, eval(f, list(x=a)), taylor(f, a, deg, 1))) )
if (curr == deg+1) return ( 0 )
## Build each additional term
return (
as.call(list(`+`,
as.call(list(`/`,
as.call(list(`*`,
eval(D(f, "x"), list(x=a)),
as.call(list(`^`, as.call(list(`-`, quote(x), a)), curr)))),
prod(1:curr))),
taylor(D(f, "x"), a, deg, curr=curr+1)))
)
}
You can see the expression that returns
## You function, parameters
f <- function(x) sin(x)
a <- 0
(t3 <- taylor(f, a, 3))
# .Primitive("+")(0, .Primitive("+")(.Primitive("/")(.Primitive("*")(1,
# .Primitive("^")(.Primitive("-")(x, 0), 1)), 1), .Primitive("+")(.Primitive("/")(.Primitive("*")(0,
# .Primitive("^")(.Primitive("-")(x, 0), 2)), 2), .Primitive("+")(.Primitive("/")(.Primitive("*")(-1,
# .Primitive("^")(.Primitive("-")(x, 0), 3)), 6), 0))))
And to see if it works
## Look at it
xs <- seq(-4, 4, len=100)
curve(f, -4, 4, type="p", pch=".", cex=4, main="Approximations of sin(x) at x=1",
ylim=c(-2, 2))
cols <- colorRampPalette(c("orange", "red"))(7)
with(list(x=xs), {
for (i in 1:7)
points(xs, eval(taylor(f, a=1, i)), col=cols[i], lty=2, type="l", lwd=2)
})
+2
source to share