July 27, 2016    R R Package gist

Memoisation is a technique wherein the results of functions are cached based on inputs. For example, the following function calculates the fibonnaci sequence in R.

Note that this is a rather innefficient way of calculating values of the fibonnacci sequence. However, it is a useful example for understanding memoisation. The following code uses Hadley Wickhams package memoise.

In the above example, the memoise() function generates a memoised function, which will automatically cache results. If the function is run again with the same parameters, it will return the cached result. Implementing memoisation can significantly speed up analysis when functions that take time to run are repeatedly called.

What if you are running similar analyses within a cluster environment? The ability to cache results in a centralized datastore could increase the speed of analysis across all machines. Alternatively, perhaps you work on different computers at work and at home. Forgetting to save/load intermediate files may require long-running functions to be run again. Further, managing and retaining intermediate files can be cumbersome and annoying. Again, caching the results of memoised function in a central location (e.g. cloud-based storage) can speed up analytical pipelines across machines.

Recently I’ve put some work into developing additional caches for the memoise package available here. This version can be used to cache items locally or remotely in a variety of environments. Supported environments include:

  • R environment (cache_local)
  • Google Datastore (cache_datastore)
  • Amazon S3 (cache_aws_s3)
  • File system (cache_filesystem; allows dropbox, google drive to be used for caching)

There are a few caveats to consider when using this version of memoise. If you use the external cache options, it will take additional time to retrieve cached items. This is preferable in cluster environments where syncing files across instances/nodes can be difficult. However, when working at home/work, using locally synced files is preferable.

Installation

devtools::install_github("danielecook/memoise")

Usage

Google Datastore

Amazon S3