How to have a Memoise cached function remain cached after package rebuild in R

302 Views Asked by At

I use the Memoise package to cache function calls in an R package I am developing. During development, I regularly rebuild my package. But every time I do, the cached function calls are forgotten. Any suggestions on how to keep these function calls cached? Preferably using the Memoise package. But if not possible, an alternative suggestion will be appreciated.

To reproduce from scratch, do this:

Part 1 - Create Package

On interactive R console, create a package called "TmpTestPackage1". (This will create a directory called "TmpTestPackage1" in your current working directory):

> library("devtools")
> create("TmpTestPackage1")

Create the file ./TmpTestPackage1/R/SomeCode.R and insert content:

library("memoise")

longFunction = function() {
    Sys.sleep(5)
    return(7)
}

cachedLongFunction = memoise::memoise(longFunction)

someOtherFunction = function() {    
    return(cachedLongFunction())
}

And now on an R console (from the parent directory of the TmpTestPackage1 directory, with devtools still available):

> library("devtools")
> install("TmpTestPackage1")

PART 2 - Reproduce my problem

> library("TmpTestPackage1")
> someOtherFunction() # This waits for 5 seconds as expected
> someOtherFunction() # Now completes almost immediately because
                      # the function call is cached. Good.
> install("TmpTestPackage1")
> someOtherFunction() # This waits 5 seconds again! I want it to
                      # still be cached however.
1

There are 1 best solutions below

0
On BEST ANSWER

By default the cache is in memory, which get cleared in package rebuilding since R session was restarted.

You can use filesystem cache in memoise, for example keep the cache in the inst folder.