3

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")`
zephryl
  • 14,633
  • 3
  • 11
  • 30
José
  • 33
  • 4
  • 1
    This is a scoping issue and the package maintainer should solve it. They should pass the correct environment when they call `eval` internally. I suggest you report this to the package maintainer. – Roland Dec 14 '22 at 07:02

1 Answers1

3

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

TarJae
  • 72,363
  • 6
  • 19
  • 66