Skip to content
Prev 363617 / 398502 Next

How to test existence of an environment and how to remove it (from within functions)?

Dear Duncan,

Thanks a lot for your help.

I tried to adapt your example to my MWE, but the subsequent calls of
main() are 'too fast' now: new calls of main() should also 'reset' the
environment (as a different x is generated then), that's why I tried
to remove the environment .my_environ from within main():

## Auxiliary function with caching
aux <- local({
    .my_environ <- new.env(hash = FALSE, parent = emptyenv()) # define
the environment
    function(x) {
        ## Setting up the environment and caching
        if(exists("cached.obj", envir = .my_environ)) { # look-up (in
case the object already exists)
            x.cols <- get("cached.obj", .my_environ)
        } else { # time-consuming part (+ cache)
            x.cols <- split(x, col(x))
            Sys.sleep(1)
            assign("cached.obj", x.cols, envir = .my_environ)
        }
        ## Do something with the result from above (here: pick out two randomly
        ## chosen columns)
        x.cols[sample(1:1000, size = 2)]
    }
})

## Main function
main <- function() {
    x <- matrix(rnorm(100*1000), ncol = 1000)
    res <- replicate(5, aux(x))
    rm(.my_environ) # TODO: Trying to remove the environment
    res
}

## Testing
set.seed(271)
system.time(main()) # => ~ 1s since the cached object is found
system.time(main()) # => ~ 0s (instead of ~ 1s)
system.time(main()) # => ~ 0s (instead of ~ 1s)

Do you know a solution for this?

Background information:
This is indeed a problem from a package which draws many (sub)plots
within a single plot. Each single (sub)plot needs to access the data
for plotting but does not known about the other (sub)plots... Thought
this might be interesting in general for caching results.

Thanks & cheers,
Marius



On Mon, Aug 29, 2016 at 7:59 PM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote: