(R) Curve function: 'expr' did not evaluate to an object of length 'n'

66 Views Asked by At

I'm trying to graph a function (from user input) and some of its Taylor Series approximations in R. I'm having no trouble graphing the user's function, but have failed several times trying to graph its approximations. My latest attempt involved the pracma package's taylor() function, but still to no avail. Here is my code:

  output$plot1 <- renderPlot({
    tempTxt2 <- parse(text=input$userTxtVar)
    f1 <- Vectorize(function(x){ return(eval(tempTxt2))})
    a <- as.numeric(input$userPoint)
    taylor1 = Vectorize(function(x){return((taylor(f1, a, n=2)))})
    curve(expr = f1, from = 0, to =3)
    curve(taylor1, col = 2, add = TRUE) #line that has the error
  })
  

Normally this error is resolved by using Vectorize(), but no luck here. I guess I don't understand the taylor() function; could anyone help?

1

There are 1 best solutions below

0
Hans W. On

If you check the help page for taylor or go through your function line by line, you will recognize that the 'taylor ' function does not return the value of the taylor expansion, but a vector of polynomial coefficients. Applying Vectorizeto it does not make sense.

library(pracma)
f1 = Vectorize( function(x) sin(x) )  # as an example

a = 0.0  # as.numeric(input$userPoint)
taylor1 = function(x) polyval(taylor(f1, a, n=4), x)

curve(expr = f1, from = 0, to = 3)
curve(taylor1, col = 2, add = TRUE)
grid()

The taylor1 function is vectorized because polyval (the "Horner scheme") automatically generates a vectorized function, calculating a polynomial at all input values.