Home > Net >  How can I convert a user-input in a function in R?
How can I convert a user-input in a function in R?

Time:05-27

I am trying to develop a UDF function in R, which should work like this:

  • user write a mathematical equation (eg 2*x 4)
  • My function should convert the input in a R-function and integrate it with lower/upper limits (0 and 1)

so, myfunction(2*x 4) have to solve this problem and show 5 as output.

What I've tried:

myfunction <- function(x, low, up) {

        user_input <- function(x){}
        res <- integrate(user_input, lower = low, upper = up)
        
return(res)
   }

myfunction(2*x 4, low = 0, up = 1)

Error:

Error in integrate(user_input, lower = low, upper = up) : evaluation of function gave a result of wrong length


sure, I could do the following:

integrand <- function(x){2*x 4}
integrate(integrand, lower = 0, upper = 1)

but thats not what I am looking for.

I would be very happy about some hints.

CodePudding user response:

We can do

myfunction <- function(y, low, up) {

        user_input <- as.function(c(alist(x = ), list(substitute(y))))
        res <- integrate(user_input, lower = low, upper = up)
        
return(res)

   }

-testing

myfunction(2*x 4, low = 0, up = 1)
5 with absolute error < 5.6e-14
  • Related