Home > front end >  R: Converting expression to function for integral
R: Converting expression to function for integral

Time:09-30

My goal is to integrate the square of the derivative of a differentiable function between 0 and 1: I've tried 2 codes: Attempt 1:

expToFunc <- function(f) {
  #input as an expression in terms of x
  function(x) eval(f)
}

int <- function(f) {
  Df2 <- substitute(expression(y^2), list(y = D(f,'x')))
  integrate(expToFunc(Df2),0,1)
}

int(expression(x*(x-1)))

Returns Error in integrate(expToFunc(Df2), 0, 1) : evaluation of function gave a result of wrong length., I think my first function isn't acting as intended expToFunc(expression(x*(x-1))) returns function(x) eval(f), and so the code interpreted the f as that letter and not the input?

Attempt 2 is similar, with a change in attempting to convert from expression to function by using the expression string

expToFunc <- function(str) {
  #input as a string in terms of x
  function(x) str
}

int <- function(f) {
  Df2 <- substitute(expression(y^2), list(y = D(f,'x')))
  integrate(expToFunc(Df2[[1]]),0,1)
}

int(expression(x*(x-1)))

which return the same thing as Attempt 1, as well as with Df2[[2]] in the place of Df2[[1]] as confusingly

Df2 <- substitute(expression(y^2), list(y = D(expression(x * (x-1)),'x')))
Df2[[1]]
% expression
Df2[[2]]
% ((x - 1)   x)^2

I'm clearly missing something with the expression class or integrate function, but I'm not sure what. Any help is greatly appreciated.

CodePudding user response:

1) Evaluate the expression and assign it to the body of a function f. Then integrate f.

int <- function(expr) {
  f <- function(x) {}
  body(f) <- eval(substitute(expression(y^2), list(y = D(expr,'x'))))
  integrate(f, 0, 1)
}

int(expression(x*(x-1)))
## .3333333 with absolute error < 3.7e-15

2) This variation also works.

int2 <- function(expr) {
  f <- function(x) {}
  body(f) <- eval(substitute(D(expr, "x")))
  integrate(function(x) f(x)^2, 0, 1)
}

int2(expression(x * (x - 1)))
## .3333333 with absolute error < 3.7e-15

3) as.function.formula in the gsubfn package can turn a formula into a function.

library(gsubfn)
int3 <- function(fo) {
  integrate(function(x) as.function(fo)(x)^2, 0, 1)
}

int3(~ x*(x-1))
## .3333333 with absolute error < 3.7e-15
  •  Tags:  
  • r
  • Related