Search code examples
rfunctionexpressioncustomization

How can I customize an object of the class "expression"? I need to write a function for which the parameters change


I am trying to write an expression for which I need to find the parameters, but once I define the parameters to come from another variable, the expression does not recognize them. For example:

This works fine:

expression(2*x*exp(-3*t))

I get:

expression(2 * x * exp(-3 * t))

But the issue is that I don't know if 2 and 3 are the right values (I'm trying to find them). So I tried to put this into a function like this:

 exp.fx <- function(params){
   u         <- params[1]
   D         <- params[2]
   expr1     <- expression(u*x*exp(-D*t))
   
   return(expr1)
}

And this is what I get:

> exp.fx(c(2,3))
u * x * exp(-D * t)

I need to get instead

2 * x * exp(-3 * t)

Bottom line, I need to put these two parameters into an optim so I can try to find them and that's why I need a function that changes the expression each time accordingly.


Solution

  • What you are looking for is interpolation or injection. There are lots of different ways of achieving it. My favourite way is to use bquote instead of quote/expression:

    exp_fx <- function (params) {
        u <- params[1L]
        D <- params[2L]
        bquote(.(u) * x * exp(-.(D) * t))
    }
    

    (Note that there’s no need for the expr variable, or for the return() function call; I’ve also replaced the . in the function name by _ since . can lead to confusion with S3 methods, and is therefore potentially problematic.)

    An alternative is to use substitute:

    exp_fx <- function (params) {
        substitute(
            u * x * exp(-D * t),
            list(u = params[1L], D = params[2L])
        )
    }