rfunctionexpressionnse

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)

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