Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading