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

I'm trying to create a function with expression() inside, but I get an error

I want to create this function

library(sde)

myfunction <- function(r,a,K,vi){
  set.seed(123)
  d <- expression(r*x*(K-x))
  s <- expression(a*x*(K-x))
  sde.sim(X0=1,drift=d, sigma=s,M=3) -> X
  plot(X, main="Multiple")
}

but when I run the function:

myfunction(r=0.5,a=0.35,K=100,vi=1)

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

I get

Error in eval(drift) : object 'r' not found

Why can’t R find the objects inside the expression()?

I get the desired result, outside the function and assigning the values; but I want a function to do this. The problem is R doesn’t find the values inside the expression(), inside the function.

r <- 0.5  
a <- 0.35  
K <- 20  
vi <- 1  
set.seed(123)  
d <- expression(r*x*(K-x))
s <- expression(ax(K-x))
sde.sim(X0=1,drift=d, sigma=s,M=3) -> X
plot(X, main="Multiple")`

>Solution :

One way to solve is to use bquote together with .(). bquote evaluates the expression enclosed in .():

library(sde)
myfunction <- function(r,a,K,vi){
  set.seed(123)
  d <- as.expression(bquote(.(r)*x*(.(K)-x)))
  s <- as.expression(bquote(.(a)*x*(.(K)-x)))
  sde.sim(X0=1,drift=d, sigma=s,M=3) -> X
  plot(X, main="Multiple")
}

myfunction(r=0.5,a=0.35,K=100,vi=1)

enter image description here

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