I’m using the IMIS package (Incremental Mixture Importance Sampling) to estimate parameters. Unfortunately, it’s written to look for functions likelihood, sample.prior, and prior in the environment it’s called in, so I can’t wrap it in a function (my end goal). The univariate example from ?IMIS works just fine,
require(IMIS)
likelihood <- function(theta) exp(-1*sin(3*theta)*sin(theta^2) - 0.1*theta^2)
prior <- function(theta) dnorm(theta, 0, 5)
sample.prior <- function(n) rnorm(n, 0, 5)
result = IMIS(500, 3000, 100, 10)
## also fine using do.call (pertinent below)
result <- do.call(IMIS, args = list(B = 500, B.re = 3000, number_k = 100, D = 10))
but unsurprisingly, wrapping it in a function does not:
rm(likelihood, prior, sample.prior, result)
imisWrap <- function() {
likelihood <- function(theta) exp(-1*sin(3*theta)*sin(theta^2) - 0.1*theta^2)
prior <- function(theta) dnorm(theta, 0, 5)
sample.prior <- function(n) rnorm(n, 0, 5)
result = IMIS(500, 3000, 100, 10)
return(result)
}
imisWrap() ## can't find sample.prior
I think the way around this is to create an environment in my wrapper (or use its environment) and then use do.call to run IMIS in that environment, but I don’t know how to create a new environment that has likelihood, prior, sample.prior, and result in it.
Edit: Using @BenBolker’s excellent comments I have an improved but still not working attempt:
imisWrap2 <- function() {
likelihood <- function(theta) exp(-1*sin(3*theta)*sin(theta^2) - 0.1*theta^2)
prior <- function(theta) dnorm(theta, 0, 5)
sample.prior <- function(n) rnorm(n, 0, 5)
imisEnv <- new.env()
assign("likelihood", likelihood, envir = imisEnv)
assign("sample.prior", sample.prior, envir = imisEnv)
assign("prior", prior, envir = imisEnv)
result = do.call(IMIS,
args = list(B = 500, B.re = 3000, number_k = 100, D = 10),
envir = imisEnv)
return(result)
}
But this still can’t find the functions.
You can put
environment(IMIS) <- environment()at the top ofimisWrapto get it to work. This only modifies the behavior ofIMISinimisWrap. The version of the function in the package namespace is unchanged.